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;
17 use rustc::hir::def_id::{CrateNum, DefIndex};
18 use rustc::hir::svh::Svh;
19 use rustc::middle::cstore::DepKind;
20 use rustc::session::{config, Session};
21 use rustc_back::PanicStrategy;
22 use rustc::session::search_paths::PathKind;
24 use rustc::middle::cstore::{CrateStore, validate_crate_name, ExternCrate};
25 use rustc::util::common::record_time;
26 use rustc::util::nodemap::FxHashSet;
27 use rustc::middle::cstore::NativeLibrary;
28 use rustc::hir::map::Definitions;
30 use std::cell::{RefCell, Cell};
32 use std::path::PathBuf;
39 use syntax::ext::base::SyntaxExtension;
40 use syntax::feature_gate::{self, GateIssue};
41 use syntax::symbol::Symbol;
42 use syntax_pos::{Span, DUMMY_SP};
46 pub dylib: Option<(PathBuf, PathKind)>,
47 pub rlib: Option<(PathBuf, PathKind)>,
48 pub rmeta: Option<(PathBuf, PathKind)>,
49 pub metadata: MetadataBlob,
52 pub struct CrateLoader<'a> {
53 pub sess: &'a Session,
55 next_crate_num: CrateNum,
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.name());
63 info!(" cnum: {}", data.cnum);
64 info!(" hash: {}", data.hash());
65 info!(" reqd: {:?}", data.dep_kind.get());
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()));
74 struct ExternCrateInfo {
81 fn register_native_lib(sess: &Session,
85 if lib.name.as_str().is_empty() {
88 struct_span_err!(sess, span, E0454,
89 "#[link(name = \"\")] given with empty name")
90 .span_label(span, &format!("empty name given"))
94 sess.err("empty library name given via `-l`");
99 let is_osx = sess.target.target.options.is_like_osx;
100 if lib.kind == cstore::NativeFramework && !is_osx {
101 let msg = "native frameworks are only available on OSX targets";
103 Some(span) => span_err!(sess, span, E0455, "{}", msg),
104 None => sess.err(msg),
107 if lib.cfg.is_some() && !sess.features.borrow().link_cfg {
108 feature_gate::emit_feature_err(&sess.parse_sess,
114 if lib.kind == cstore::NativeStaticNobundle && !sess.features.borrow().static_nobundle {
115 feature_gate::emit_feature_err(&sess.parse_sess,
119 "kind=\"static-nobundle\" is feature gated");
121 cstore.add_used_library(lib);
124 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
126 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
131 // Extra info about a crate loaded for plugins or exported macros.
132 struct ExtensionCrate {
134 dylib: Option<PathBuf>,
139 Registered(Rc<cstore::CrateMetadata>),
143 impl Deref for PMDSource {
144 type Target = MetadataBlob;
146 fn deref(&self) -> &MetadataBlob {
148 PMDSource::Registered(ref cmd) => &cmd.blob,
149 PMDSource::Owned(ref lib) => &lib.metadata
159 impl<'a> CrateLoader<'a> {
160 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
164 next_crate_num: cstore.next_crate_num(),
165 local_crate_name: Symbol::intern(local_crate_name),
169 fn extract_crate_info(&self, i: &ast::Item) -> Option<ExternCrateInfo> {
171 ast::ItemKind::ExternCrate(ref path_opt) => {
172 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
174 let name = match *path_opt {
176 validate_crate_name(Some(self.sess), &name.as_str(),
180 None => i.ident.name,
182 Some(ExternCrateInfo {
186 dep_kind: if attr::contains_name(&i.attrs, "no_link") {
187 DepKind::UnexportedMacrosOnly
197 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
198 -> Option<CrateNum> {
200 self.cstore.iter_crate_data(|cnum, data| {
201 if data.name != name { return }
204 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
209 // When the hash is None we're dealing with a top-level dependency
210 // in which case we may have a specification on the command line for
211 // this library. Even though an upstream library may have loaded
212 // something of the same name, we have to make sure it was loaded
213 // from the exact same location as well.
215 // We're also sure to compare *paths*, not actual byte slices. The
216 // `source` stores paths which are normalized which may be different
217 // from the strings on the command line.
218 let source = self.cstore.used_crate_source(cnum);
219 if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
220 let found = locs.iter().any(|l| {
221 let l = fs::canonicalize(l).ok();
222 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
223 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
231 // Alright, so we've gotten this far which means that `data` has the
232 // right name, we don't have a hash, and we don't have a --extern
233 // pointing for ourselves. We're still not quite yet done because we
234 // have to make sure that this crate was found in the crate lookup
235 // path (this is a top-level dependency) as we don't want to
236 // implicitly load anything inside the dependency lookup path.
237 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
239 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
246 fn verify_no_symbol_conflicts(&self,
249 // Check for (potential) conflicts with the local crate
250 if self.local_crate_name == root.name &&
251 self.sess.local_crate_disambiguator() == root.disambiguator {
252 span_fatal!(self.sess, span, E0519,
253 "the current crate is indistinguishable from one of its \
254 dependencies: it has the same crate-name `{}` and was \
255 compiled with the same `-C metadata` arguments. This \
256 will result in symbol conflicts between the two.",
260 // Check for conflicts with any crate loaded so far
261 self.cstore.iter_crate_data(|_, other| {
262 if other.name() == root.name && // same crate-name
263 other.disambiguator() == root.disambiguator && // same crate-disambiguator
264 other.hash() != root.hash { // but different SVH
265 span_fatal!(self.sess, span, E0523,
266 "found two different crates with name `{}` that are \
267 not distinguished by differing `-C metadata`. This \
268 will result in symbol conflicts between the two.",
274 fn register_crate(&mut self,
275 root: &Option<CratePaths>,
281 -> (CrateNum, Rc<cstore::CrateMetadata>) {
282 info!("register crate `extern crate {} as {}`", name, ident);
283 let crate_root = lib.metadata.get_root();
284 self.verify_no_symbol_conflicts(span, &crate_root);
286 // Claim this crate number and cache it
287 let cnum = self.next_crate_num;
288 self.next_crate_num = CrateNum::from_u32(cnum.as_u32() + 1);
290 // Stash paths for top-most crate locally if necessary.
291 let crate_paths = if root.is_none() {
293 ident: ident.to_string(),
294 dylib: lib.dylib.clone().map(|p| p.0),
295 rlib: lib.rlib.clone().map(|p| p.0),
296 rmeta: lib.rmeta.clone().map(|p| p.0),
301 // Maintain a reference to the top most crate.
302 let root = if root.is_some() { root } else { &crate_paths };
304 let Library { dylib, rlib, rmeta, metadata } = lib;
306 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
308 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
309 crate_root.def_path_table.decode(&metadata)
312 let exported_symbols = crate_root.exported_symbols.decode(&metadata).collect();
314 let mut cmeta = cstore::CrateMetadata {
316 extern_crate: Cell::new(None),
317 def_path_table: def_path_table,
318 exported_symbols: exported_symbols,
319 proc_macros: crate_root.macro_derive_registrar.map(|_| {
320 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
324 cnum_map: RefCell::new(cnum_map),
326 codemap_import_info: RefCell::new(vec![]),
327 dep_kind: Cell::new(dep_kind),
328 source: cstore::CrateSource {
333 dllimport_foreign_items: FxHashSet(),
336 let dllimports: Vec<_> = cmeta.get_native_libraries().iter()
337 .filter(|lib| relevant_lib(self.sess, lib) &&
338 lib.kind == cstore::NativeLibraryKind::NativeUnknown)
339 .flat_map(|lib| &lib.foreign_items)
342 cmeta.dllimport_foreign_items.extend(dllimports);
344 let cmeta = Rc::new(cmeta);
345 self.cstore.set_crate_data(cnum, cmeta.clone());
349 fn resolve_crate(&mut self,
350 root: &Option<CratePaths>,
356 mut dep_kind: DepKind)
357 -> (CrateNum, Rc<cstore::CrateMetadata>) {
358 info!("resolving crate `extern crate {} as {}`", name, ident);
359 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
360 LoadResult::Previous(cnum)
362 info!("falling back to a load");
363 let mut locate_ctxt = locator::Context {
368 hash: hash.map(|a| &*a),
369 filesearch: self.sess.target_filesearch(path_kind),
370 target: &self.sess.target.target,
371 triple: &self.sess.opts.target_triple,
373 rejected_via_hash: vec![],
374 rejected_via_triple: vec![],
375 rejected_via_kind: vec![],
376 rejected_via_version: vec![],
377 rejected_via_filename: vec![],
378 should_match_name: true,
379 is_proc_macro: Some(false),
382 self.load(&mut locate_ctxt).or_else(|| {
383 dep_kind = DepKind::UnexportedMacrosOnly;
385 let mut proc_macro_locator = locator::Context {
386 target: &self.sess.host,
387 triple: config::host_triple(),
388 filesearch: self.sess.host_filesearch(path_kind),
389 rejected_via_hash: vec![],
390 rejected_via_triple: vec![],
391 rejected_via_kind: vec![],
392 rejected_via_version: vec![],
393 rejected_via_filename: vec![],
394 is_proc_macro: Some(true),
398 self.load(&mut proc_macro_locator)
399 }).unwrap_or_else(|| locate_ctxt.report_errs())
403 LoadResult::Previous(cnum) => {
404 let data = self.cstore.get_crate_data(cnum);
405 if data.root.macro_derive_registrar.is_some() {
406 dep_kind = DepKind::UnexportedMacrosOnly;
408 data.dep_kind.set(cmp::max(data.dep_kind.get(), dep_kind));
411 LoadResult::Loaded(library) => {
412 self.register_crate(root, ident, name, span, library, dep_kind)
417 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
418 let library = match locate_ctxt.maybe_load_library_crate() {
423 // In the case that we're loading a crate, but not matching
424 // against a hash, we could load a crate which has the same hash
425 // as an already loaded crate. If this is the case prevent
426 // duplicates by just using the first crate.
428 // Note that we only do this for target triple crates, though, as we
429 // don't want to match a host crate against an equivalent target one
431 let root = library.metadata.get_root();
432 if locate_ctxt.triple == self.sess.opts.target_triple {
433 let mut result = LoadResult::Loaded(library);
434 self.cstore.iter_crate_data(|cnum, data| {
435 if data.name() == root.name && root.hash == data.hash() {
436 assert!(locate_ctxt.hash.is_none());
437 info!("load success, going to previous cnum: {}", cnum);
438 result = LoadResult::Previous(cnum);
443 Some(LoadResult::Loaded(library))
447 fn update_extern_crate(&mut self,
449 mut extern_crate: ExternCrate,
450 visited: &mut FxHashSet<(CrateNum, bool)>)
452 if !visited.insert((cnum, extern_crate.direct)) { return }
454 let cmeta = self.cstore.get_crate_data(cnum);
455 let old_extern_crate = cmeta.extern_crate.get();
458 // - something over nothing (tuple.0);
459 // - direct extern crate to indirect (tuple.1);
460 // - shorter paths to longer (tuple.2).
461 let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
462 let old_rank = match old_extern_crate {
463 None => (false, false, !0),
464 Some(ref c) => (true, c.direct, !c.path_len),
467 if old_rank >= new_rank {
468 return; // no change needed
471 cmeta.extern_crate.set(Some(extern_crate));
472 // Propagate the extern crate info to dependencies.
473 extern_crate.direct = false;
474 for &dep_cnum in cmeta.cnum_map.borrow().iter() {
475 self.update_extern_crate(dep_cnum, extern_crate, visited);
479 // Go through the crate metadata and load any crates that it references
480 fn resolve_crate_deps(&mut self,
481 root: &Option<CratePaths>,
482 crate_root: &CrateRoot,
483 metadata: &MetadataBlob,
487 -> cstore::CrateNumMap {
488 debug!("resolving deps of external crate");
489 if crate_root.macro_derive_registrar.is_some() {
490 return cstore::CrateNumMap::new();
493 // The map from crate numbers in the crate we're resolving to local crate numbers.
494 // We map 0 and all other holes in the map to our parent crate. The "additional"
495 // self-dependencies should be harmless.
496 ::std::iter::once(krate).chain(crate_root.crate_deps.decode(metadata).map(|dep| {
497 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
498 if dep.kind == DepKind::UnexportedMacrosOnly {
501 let dep_kind = match dep_kind {
502 DepKind::MacrosOnly => DepKind::MacrosOnly,
505 let (local_cnum, ..) = self.resolve_crate(
506 root, dep.name, dep.name, Some(&dep.hash), span, PathKind::Dependency, dep_kind,
512 fn read_extension_crate(&mut self, span: Span, info: &ExternCrateInfo) -> ExtensionCrate {
513 info!("read extension crate {} `extern crate {} as {}` dep_kind={:?}",
514 info.id, info.name, info.ident, info.dep_kind);
515 let target_triple = &self.sess.opts.target_triple[..];
516 let is_cross = target_triple != config::host_triple();
517 let mut target_only = false;
518 let mut locate_ctxt = locator::Context {
522 crate_name: info.name,
524 filesearch: self.sess.host_filesearch(PathKind::Crate),
525 target: &self.sess.host,
526 triple: config::host_triple(),
528 rejected_via_hash: vec![],
529 rejected_via_triple: vec![],
530 rejected_via_kind: vec![],
531 rejected_via_version: vec![],
532 rejected_via_filename: vec![],
533 should_match_name: true,
536 let library = self.load(&mut locate_ctxt).or_else(|| {
540 // Try loading from target crates. This will abort later if we
541 // try to load a plugin registrar function,
544 locate_ctxt.target = &self.sess.target.target;
545 locate_ctxt.triple = target_triple;
546 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
548 self.load(&mut locate_ctxt)
550 let library = match library {
552 None => locate_ctxt.report_errs(),
555 let (dylib, metadata) = match library {
556 LoadResult::Previous(cnum) => {
557 let data = self.cstore.get_crate_data(cnum);
558 (data.source.dylib.clone(), PMDSource::Registered(data))
560 LoadResult::Loaded(library) => {
561 let dylib = library.dylib.clone();
562 let metadata = PMDSource::Owned(library);
569 dylib: dylib.map(|p| p.0),
570 target_only: target_only,
574 /// Load custom derive macros.
576 /// Note that this is intentionally similar to how we load plugins today,
577 /// but also intentionally separate. Plugins are likely always going to be
578 /// implemented as dynamic libraries, but we have a possible future where
579 /// custom derive (and other macro-1.1 style features) are implemented via
580 /// executables and custom IPC.
581 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
582 -> Vec<(ast::Name, Rc<SyntaxExtension>)> {
584 use proc_macro::TokenStream;
585 use proc_macro::__internal::Registry;
586 use rustc_back::dynamic_lib::DynamicLibrary;
587 use syntax_ext::deriving::custom::ProcMacroDerive;
588 use syntax_ext::proc_macro_impl::AttrProcMacro;
590 let path = match dylib {
591 Some(dylib) => dylib,
592 None => span_bug!(span, "proc-macro crate not dylib"),
594 // Make sure the path contains a / or the linker will search for it.
595 let path = env::current_dir().unwrap().join(path);
596 let lib = match DynamicLibrary::open(Some(&path)) {
598 Err(err) => self.sess.span_fatal(span, &err),
601 let sym = self.sess.generate_derive_registrar_symbol(&root.hash,
602 root.macro_derive_registrar.unwrap());
603 let registrar = unsafe {
604 let sym = match lib.symbol(&sym) {
606 Err(err) => self.sess.span_fatal(span, &err),
608 mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
611 struct MyRegistrar(Vec<(ast::Name, Rc<SyntaxExtension>)>);
613 impl Registry for MyRegistrar {
614 fn register_custom_derive(&mut self,
616 expand: fn(TokenStream) -> TokenStream,
617 attributes: &[&'static str]) {
618 let attrs = attributes.iter().cloned().map(Symbol::intern).collect();
619 let derive = SyntaxExtension::ProcMacroDerive(
620 Box::new(ProcMacroDerive::new(expand, attrs))
622 self.0.push((Symbol::intern(trait_name), Rc::new(derive)));
625 fn register_attr_proc_macro(&mut self,
627 expand: fn(TokenStream, TokenStream) -> TokenStream) {
628 let expand = SyntaxExtension::AttrProcMacro(
629 Box::new(AttrProcMacro { inner: expand })
631 self.0.push((Symbol::intern(name), Rc::new(expand)));
635 let mut my_registrar = MyRegistrar(Vec::new());
636 registrar(&mut my_registrar);
638 // Intentionally leak the dynamic library. We can't ever unload it
639 // since the library can make things that will live arbitrarily long.
644 /// Look for a plugin registrar. Returns library path, crate
645 /// SVH and DefIndex of the registrar function.
646 pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
647 -> Option<(PathBuf, Svh, DefIndex)> {
648 let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
649 name: Symbol::intern(name),
650 ident: Symbol::intern(name),
651 id: ast::DUMMY_NODE_ID,
652 dep_kind: DepKind::UnexportedMacrosOnly,
655 if ekrate.target_only {
656 // Need to abort before syntax expansion.
657 let message = format!("plugin `{}` is not available for triple `{}` \
660 config::host_triple(),
661 self.sess.opts.target_triple);
662 span_fatal!(self.sess, span, E0456, "{}", &message[..]);
665 let root = ekrate.metadata.get_root();
666 match (ekrate.dylib.as_ref(), root.plugin_registrar_fn) {
667 (Some(dylib), Some(reg)) => {
668 Some((dylib.to_path_buf(), root.hash, reg))
671 span_err!(self.sess, span, E0457,
672 "plugin `{}` only found in rlib format, but must be available \
675 // No need to abort because the loading code will just ignore this
683 fn get_foreign_items_of_kind(&self, kind: cstore::NativeLibraryKind) -> Vec<DefIndex> {
684 let mut items = vec![];
685 let libs = self.cstore.get_used_libraries();
686 for lib in libs.borrow().iter() {
687 if relevant_lib(self.sess, lib) && lib.kind == kind {
688 items.extend(&lib.foreign_items);
694 fn register_statically_included_foreign_items(&mut self) {
695 for id in self.get_foreign_items_of_kind(cstore::NativeStatic) {
696 self.cstore.add_statically_included_foreign_item(id);
698 for id in self.get_foreign_items_of_kind(cstore::NativeStaticNobundle) {
699 self.cstore.add_statically_included_foreign_item(id);
703 fn register_dllimport_foreign_items(&mut self) {
704 let mut dllimports = self.cstore.dllimport_foreign_items.borrow_mut();
705 for id in self.get_foreign_items_of_kind(cstore::NativeUnknown) {
706 dllimports.insert(id);
710 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
711 // If we're only compiling an rlib, then there's no need to select a
712 // panic runtime, so we just skip this section entirely.
713 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
714 *ct != config::CrateTypeRlib
717 info!("panic runtime injection skipped, only generating rlib");
721 // If we need a panic runtime, we try to find an existing one here. At
722 // the same time we perform some general validation of the DAG we've got
723 // going such as ensuring everything has a compatible panic strategy.
725 // The logic for finding the panic runtime here is pretty much the same
726 // as the allocator case with the only addition that the panic strategy
727 // compilation mode also comes into play.
728 let desired_strategy = self.sess.panic_strategy();
729 let mut runtime_found = false;
730 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
731 "needs_panic_runtime");
732 self.cstore.iter_crate_data(|cnum, data| {
733 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
734 if data.is_panic_runtime() {
735 // Inject a dependency from all #![needs_panic_runtime] to this
736 // #![panic_runtime] crate.
737 self.inject_dependency_if(cnum, "a panic runtime",
738 &|data| data.needs_panic_runtime());
739 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
743 // If an explicitly linked and matching panic runtime was found, or if
744 // we just don't need one at all, then we're done here and there's
745 // nothing else to do.
746 if !needs_panic_runtime || runtime_found {
750 // By this point we know that we (a) need a panic runtime and (b) no
751 // panic runtime was explicitly linked. Here we just load an appropriate
752 // default runtime for our panic strategy and then inject the
755 // We may resolve to an already loaded crate (as the crate may not have
756 // been explicitly linked prior to this) and we may re-inject
757 // dependencies again, but both of those situations are fine.
759 // Also note that we have yet to perform validation of the crate graph
760 // in terms of everyone has a compatible panic runtime format, that's
761 // performed later as part of the `dependency_format` module.
762 let name = match desired_strategy {
763 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
764 PanicStrategy::Abort => Symbol::intern("panic_abort"),
766 info!("panic runtime not found -- loading {}", name);
768 let dep_kind = DepKind::Implicit;
770 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
772 // Sanity check the loaded crate to ensure it is indeed a panic runtime
773 // and the panic strategy is indeed what we thought it was.
774 if !data.is_panic_runtime() {
775 self.sess.err(&format!("the crate `{}` is not a panic runtime",
778 if data.panic_strategy() != desired_strategy {
779 self.sess.err(&format!("the crate `{}` does not have the panic \
781 name, desired_strategy.desc()));
784 self.sess.injected_panic_runtime.set(Some(cnum));
785 self.inject_dependency_if(cnum, "a panic runtime",
786 &|data| data.needs_panic_runtime());
789 fn inject_allocator_crate(&mut self) {
790 // Make sure that we actually need an allocator, if none of our
791 // dependencies need one then we definitely don't!
793 // Also, if one of our dependencies has an explicit allocator, then we
794 // also bail out as we don't need to implicitly inject one.
795 let mut needs_allocator = false;
796 let mut found_required_allocator = false;
797 self.cstore.iter_crate_data(|cnum, data| {
798 needs_allocator = needs_allocator || data.needs_allocator();
799 if data.is_allocator() {
800 info!("{} required by rlib and is an allocator", data.name());
801 self.inject_dependency_if(cnum, "an allocator",
802 &|data| data.needs_allocator());
803 found_required_allocator = found_required_allocator ||
804 data.dep_kind.get() == DepKind::Explicit;
807 if !needs_allocator || found_required_allocator { return }
809 // At this point we've determined that we need an allocator and no
810 // previous allocator has been activated. We look through our outputs of
811 // crate types to see what kind of allocator types we may need.
813 // The main special output type here is that rlibs do **not** need an
814 // allocator linked in (they're just object files), only final products
815 // (exes, dylibs, staticlibs) need allocators.
816 let mut need_lib_alloc = false;
817 let mut need_exe_alloc = false;
818 for ct in self.sess.crate_types.borrow().iter() {
820 config::CrateTypeExecutable => need_exe_alloc = true,
821 config::CrateTypeDylib |
822 config::CrateTypeProcMacro |
823 config::CrateTypeCdylib |
824 config::CrateTypeStaticlib => need_lib_alloc = true,
825 config::CrateTypeRlib => {}
828 if !need_lib_alloc && !need_exe_alloc { return }
830 // The default allocator crate comes from the custom target spec, and we
831 // choose between the standard library allocator or exe allocator. This
832 // distinction exists because the default allocator for binaries (where
833 // the world is Rust) is different than library (where the world is
834 // likely *not* Rust).
836 // If a library is being produced, but we're also flagged with `-C
837 // prefer-dynamic`, then we interpret this as a *Rust* dynamic library
838 // is being produced so we use the exe allocator instead.
840 // What this boils down to is:
842 // * Binaries use jemalloc
843 // * Staticlibs and Rust dylibs use system malloc
844 // * Rust dylibs used as dependencies to rust use jemalloc
845 let name = if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
846 Symbol::intern(&self.sess.target.target.options.lib_allocation_crate)
848 Symbol::intern(&self.sess.target.target.options.exe_allocation_crate)
850 let dep_kind = DepKind::Implicit;
852 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
854 // Sanity check the crate we loaded to ensure that it is indeed an
856 if !data.is_allocator() {
857 self.sess.err(&format!("the allocator crate `{}` is not tagged \
858 with #![allocator]", data.name()));
861 self.sess.injected_allocator.set(Some(cnum));
862 self.inject_dependency_if(cnum, "an allocator",
863 &|data| data.needs_allocator());
866 fn inject_dependency_if(&self,
869 needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
870 // don't perform this validation if the session has errors, as one of
871 // those errors may indicate a circular dependency which could cause
872 // this to stack overflow.
873 if self.sess.has_errors() {
877 // Before we inject any dependencies, make sure we don't inject a
878 // circular dependency by validating that this crate doesn't
879 // transitively depend on any crates satisfying `needs_dep`.
880 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
881 let data = self.cstore.get_crate_data(dep);
882 if needs_dep(&data) {
883 self.sess.err(&format!("the crate `{}` cannot depend \
884 on a crate that needs {}, but \
886 self.cstore.get_crate_data(krate).name(),
892 // All crates satisfying `needs_dep` do not explicitly depend on the
893 // crate provided for this compile, but in order for this compilation to
894 // be successfully linked we need to inject a dependency (to order the
895 // crates on the command line correctly).
896 self.cstore.iter_crate_data(|cnum, data| {
897 if !needs_dep(data) {
901 info!("injecting a dep from {} to {}", cnum, krate);
902 data.cnum_map.borrow_mut().push(krate);
907 impl<'a> CrateLoader<'a> {
908 pub fn preprocess(&mut self, krate: &ast::Crate) {
909 for attr in krate.attrs.iter().filter(|m| m.name() == "link_args") {
910 if let Some(linkarg) = attr.value_str() {
911 self.cstore.add_used_link_args(&linkarg.as_str());
916 fn process_foreign_mod(&mut self, i: &ast::Item, fm: &ast::ForeignMod,
917 definitions: &Definitions) {
918 if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
922 // First, add all of the custom #[link_args] attributes
923 for m in i.attrs.iter().filter(|a| a.check_name("link_args")) {
924 if let Some(linkarg) = m.value_str() {
925 self.cstore.add_used_link_args(&linkarg.as_str());
929 // Next, process all of the #[link(..)]-style arguments
930 for m in i.attrs.iter().filter(|a| a.check_name("link")) {
931 let items = match m.meta_item_list() {
935 let kind = items.iter().find(|k| {
937 }).and_then(|a| a.value_str()).map(Symbol::as_str);
938 let kind = match kind.as_ref().map(|s| &s[..]) {
939 Some("static") => cstore::NativeStatic,
940 Some("static-nobundle") => cstore::NativeStaticNobundle,
941 Some("dylib") => cstore::NativeUnknown,
942 Some("framework") => cstore::NativeFramework,
944 struct_span_err!(self.sess, m.span, E0458,
945 "unknown kind: `{}`", k)
946 .span_label(m.span, &format!("unknown kind")).emit();
947 cstore::NativeUnknown
949 None => cstore::NativeUnknown
951 let n = items.iter().find(|n| {
953 }).and_then(|a| a.value_str());
957 struct_span_err!(self.sess, m.span, E0459,
958 "#[link(...)] specified without `name = \"foo\"`")
959 .span_label(m.span, &format!("missing `name` argument")).emit();
960 Symbol::intern("foo")
963 let cfg = items.iter().find(|k| {
965 }).and_then(|a| a.meta_item_list());
966 let cfg = cfg.map(|list| {
967 list[0].meta_item().unwrap().clone()
969 let foreign_items = fm.items.iter()
970 .map(|it| definitions.opt_def_index(it.id).unwrap())
972 let lib = NativeLibrary {
976 foreign_items: foreign_items,
978 register_native_lib(self.sess, self.cstore, Some(m.span), lib);
983 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
984 fn postprocess(&mut self, krate: &ast::Crate) {
985 self.inject_allocator_crate();
986 self.inject_panic_runtime(krate);
988 if log_enabled!(log::INFO) {
989 dump_crates(&self.cstore);
992 // Process libs passed on the command line
993 // First, check for errors
994 let mut renames = FxHashSet();
995 for &(ref name, ref new_name, _) in &self.sess.opts.libs {
996 if let &Some(ref new_name) = new_name {
997 if new_name.is_empty() {
999 &format!("an empty renaming target was specified for library `{}`",name));
1000 } else if !self.cstore.get_used_libraries().borrow().iter()
1001 .any(|lib| lib.name == name as &str) {
1002 self.sess.err(&format!("renaming of the library `{}` was specified, \
1003 however this crate contains no #[link(...)] \
1004 attributes referencing this library.", name));
1005 } else if renames.contains(name) {
1006 self.sess.err(&format!("multiple renamings were specified for library `{}` .",
1009 renames.insert(name);
1013 // Update kind and, optionally, the name of all native libaries
1014 // (there may be more than one) with the specified name.
1015 for &(ref name, ref new_name, kind) in &self.sess.opts.libs {
1016 let mut found = false;
1017 for lib in self.cstore.get_used_libraries().borrow_mut().iter_mut() {
1018 if lib.name == name as &str {
1020 if let &Some(ref new_name) = new_name {
1021 lib.name = Symbol::intern(new_name);
1028 let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
1029 let lib = NativeLibrary {
1030 name: Symbol::intern(new_name.unwrap_or(name)),
1033 foreign_items: Vec::new(),
1035 register_native_lib(self.sess, self.cstore, None, lib);
1038 self.register_statically_included_foreign_items();
1039 self.register_dllimport_foreign_items();
1042 fn process_item(&mut self, item: &ast::Item, definitions: &Definitions) {
1044 ast::ItemKind::ForeignMod(ref fm) => {
1045 self.process_foreign_mod(item, fm, definitions)
1047 ast::ItemKind::ExternCrate(_) => {
1048 let info = self.extract_crate_info(item).unwrap();
1049 let (cnum, ..) = self.resolve_crate(
1050 &None, info.ident, info.name, None, item.span, PathKind::Crate, info.dep_kind,
1053 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1054 let len = definitions.def_path(def_id.index).data.len();
1057 ExternCrate { def_id: def_id, span: item.span, direct: true, path_len: len };
1058 self.update_extern_crate(cnum, extern_crate, &mut FxHashSet());
1059 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);