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::nodemap::{FxHashMap, FxHashSet};
26 use rustc::middle::cstore::NativeLibrary;
27 use rustc::hir::map::Definitions;
29 use std::cell::{RefCell, Cell};
31 use std::path::PathBuf;
38 use syntax::ext::base::SyntaxExtension;
39 use syntax::feature_gate::{self, GateIssue};
40 use syntax::parse::token::{InternedString, intern};
41 use syntax_pos::{Span, DUMMY_SP};
45 pub dylib: Option<(PathBuf, PathKind)>,
46 pub rlib: Option<(PathBuf, PathKind)>,
47 pub metadata: MetadataBlob,
50 pub struct CrateLoader<'a> {
51 pub sess: &'a Session,
53 next_crate_num: CrateNum,
54 foreign_item_map: FxHashMap<String, Vec<ast::NodeId>>,
55 local_crate_name: String,
58 fn dump_crates(cstore: &CStore) {
59 info!("resolved crates:");
60 cstore.iter_crate_data(|_, data| {
61 info!(" name: {}", data.name());
62 info!(" cnum: {}", data.cnum);
63 info!(" hash: {}", data.hash());
64 info!(" reqd: {:?}", data.dep_kind.get());
65 let CrateSource { dylib, rlib } = data.source.clone();
66 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
67 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
72 struct ExternCrateInfo {
79 fn register_native_lib(sess: &Session,
83 if lib.name.is_empty() {
86 struct_span_err!(sess, span, E0454,
87 "#[link(name = \"\")] given with empty name")
88 .span_label(span, &format!("empty name given"))
92 sess.err("empty library name given via `-l`");
97 let is_osx = sess.target.target.options.is_like_osx;
98 if lib.kind == cstore::NativeFramework && !is_osx {
99 let msg = "native frameworks are only available on OSX targets";
101 Some(span) => span_err!(sess, span, E0455, "{}", msg),
102 None => sess.err(msg),
105 if lib.cfg.is_some() && !sess.features.borrow().link_cfg {
106 feature_gate::emit_feature_err(&sess.parse_sess,
112 cstore.add_used_library(lib);
115 // Extra info about a crate loaded for plugins or exported macros.
116 struct ExtensionCrate {
118 dylib: Option<PathBuf>,
123 Registered(Rc<cstore::CrateMetadata>),
127 impl Deref for PMDSource {
128 type Target = MetadataBlob;
130 fn deref(&self) -> &MetadataBlob {
132 PMDSource::Registered(ref cmd) => &cmd.blob,
133 PMDSource::Owned(ref lib) => &lib.metadata
143 impl<'a> CrateLoader<'a> {
144 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
148 next_crate_num: cstore.next_crate_num(),
149 foreign_item_map: FxHashMap(),
150 local_crate_name: local_crate_name.to_owned(),
154 fn extract_crate_info(&self, i: &ast::Item) -> Option<ExternCrateInfo> {
156 ast::ItemKind::ExternCrate(ref path_opt) => {
157 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
159 let name = match *path_opt {
161 validate_crate_name(Some(self.sess), &name.as_str(),
165 None => i.ident.to_string(),
167 Some(ExternCrateInfo {
168 ident: i.ident.to_string(),
171 dep_kind: if attr::contains_name(&i.attrs, "no_link") {
182 fn existing_match(&self, name: &str, hash: Option<&Svh>, kind: PathKind)
183 -> Option<CrateNum> {
185 self.cstore.iter_crate_data(|cnum, data| {
186 if data.name != name { return }
189 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
194 // When the hash is None we're dealing with a top-level dependency
195 // in which case we may have a specification on the command line for
196 // this library. Even though an upstream library may have loaded
197 // something of the same name, we have to make sure it was loaded
198 // from the exact same location as well.
200 // We're also sure to compare *paths*, not actual byte slices. The
201 // `source` stores paths which are normalized which may be different
202 // from the strings on the command line.
203 let source = self.cstore.used_crate_source(cnum);
204 if let Some(locs) = self.sess.opts.externs.get(name) {
205 let found = locs.iter().any(|l| {
206 let l = fs::canonicalize(l).ok();
207 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
208 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
216 // Alright, so we've gotten this far which means that `data` has the
217 // right name, we don't have a hash, and we don't have a --extern
218 // pointing for ourselves. We're still not quite yet done because we
219 // have to make sure that this crate was found in the crate lookup
220 // path (this is a top-level dependency) as we don't want to
221 // implicitly load anything inside the dependency lookup path.
222 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
224 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
231 fn verify_no_symbol_conflicts(&self,
234 // Check for (potential) conflicts with the local crate
235 if self.local_crate_name == root.name &&
236 self.sess.local_crate_disambiguator() == &root.disambiguator[..] {
237 span_fatal!(self.sess, span, E0519,
238 "the current crate is indistinguishable from one of its \
239 dependencies: it has the same crate-name `{}` and was \
240 compiled with the same `-C metadata` arguments. This \
241 will result in symbol conflicts between the two.",
245 // Check for conflicts with any crate loaded so far
246 self.cstore.iter_crate_data(|_, other| {
247 if other.name() == root.name && // same crate-name
248 other.disambiguator() == root.disambiguator && // same crate-disambiguator
249 other.hash() != root.hash { // but different SVH
250 span_fatal!(self.sess, span, E0523,
251 "found two different crates with name `{}` that are \
252 not distinguished by differing `-C metadata`. This \
253 will result in symbol conflicts between the two.",
259 fn register_crate(&mut self,
260 root: &Option<CratePaths>,
266 -> (CrateNum, Rc<cstore::CrateMetadata>) {
267 info!("register crate `extern crate {} as {}`", name, ident);
268 let crate_root = lib.metadata.get_root();
269 self.verify_no_symbol_conflicts(span, &crate_root);
271 // Claim this crate number and cache it
272 let cnum = self.next_crate_num;
273 self.next_crate_num = CrateNum::from_u32(cnum.as_u32() + 1);
275 // Stash paths for top-most crate locally if necessary.
276 let crate_paths = if root.is_none() {
278 ident: ident.to_string(),
279 dylib: lib.dylib.clone().map(|p| p.0),
280 rlib: lib.rlib.clone().map(|p| p.0),
285 // Maintain a reference to the top most crate.
286 let root = if root.is_some() { root } else { &crate_paths };
288 let Library { dylib, rlib, metadata } = lib;
290 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
292 let cmeta = Rc::new(cstore::CrateMetadata {
293 name: name.to_string(),
294 extern_crate: Cell::new(None),
295 key_map: metadata.load_key_map(crate_root.index),
296 proc_macros: crate_root.macro_derive_registrar.map(|_| {
297 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
301 cnum_map: RefCell::new(cnum_map),
303 codemap_import_info: RefCell::new(vec![]),
304 dep_kind: Cell::new(dep_kind),
305 source: cstore::CrateSource {
311 self.cstore.set_crate_data(cnum, cmeta.clone());
315 fn resolve_crate(&mut self,
316 root: &Option<CratePaths>,
322 mut dep_kind: DepKind)
323 -> (CrateNum, Rc<cstore::CrateMetadata>) {
324 info!("resolving crate `extern crate {} as {}`", name, ident);
325 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
326 LoadResult::Previous(cnum)
328 info!("falling back to a load");
329 let mut locate_ctxt = locator::Context {
334 hash: hash.map(|a| &*a),
335 filesearch: self.sess.target_filesearch(path_kind),
336 target: &self.sess.target.target,
337 triple: &self.sess.opts.target_triple,
339 rejected_via_hash: vec![],
340 rejected_via_triple: vec![],
341 rejected_via_kind: vec![],
342 rejected_via_version: vec![],
343 should_match_name: true,
344 is_proc_macro: Some(false),
347 self.load(&mut locate_ctxt).or_else(|| {
348 dep_kind = DepKind::MacrosOnly;
350 let mut proc_macro_locator = locator::Context {
351 target: &self.sess.host,
352 triple: config::host_triple(),
353 filesearch: self.sess.host_filesearch(path_kind),
354 rejected_via_hash: vec![],
355 rejected_via_triple: vec![],
356 rejected_via_kind: vec![],
357 rejected_via_version: vec![],
358 is_proc_macro: Some(true),
362 self.load(&mut proc_macro_locator)
363 }).unwrap_or_else(|| locate_ctxt.report_errs())
367 LoadResult::Previous(cnum) => {
368 let data = self.cstore.get_crate_data(cnum);
369 data.dep_kind.set(cmp::max(data.dep_kind.get(), dep_kind));
372 LoadResult::Loaded(library) => {
373 self.register_crate(root, ident, name, span, library, dep_kind)
378 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
379 let library = match locate_ctxt.maybe_load_library_crate() {
384 // In the case that we're loading a crate, but not matching
385 // against a hash, we could load a crate which has the same hash
386 // as an already loaded crate. If this is the case prevent
387 // duplicates by just using the first crate.
389 // Note that we only do this for target triple crates, though, as we
390 // don't want to match a host crate against an equivalent target one
392 let root = library.metadata.get_root();
393 if locate_ctxt.triple == self.sess.opts.target_triple {
394 let mut result = LoadResult::Loaded(library);
395 self.cstore.iter_crate_data(|cnum, data| {
396 if data.name() == root.name && root.hash == data.hash() {
397 assert!(locate_ctxt.hash.is_none());
398 info!("load success, going to previous cnum: {}", cnum);
399 result = LoadResult::Previous(cnum);
404 Some(LoadResult::Loaded(library))
408 fn update_extern_crate(&mut self,
410 mut extern_crate: ExternCrate,
411 visited: &mut FxHashSet<(CrateNum, bool)>)
413 if !visited.insert((cnum, extern_crate.direct)) { return }
415 let cmeta = self.cstore.get_crate_data(cnum);
416 let old_extern_crate = cmeta.extern_crate.get();
419 // - something over nothing (tuple.0);
420 // - direct extern crate to indirect (tuple.1);
421 // - shorter paths to longer (tuple.2).
422 let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
423 let old_rank = match old_extern_crate {
424 None => (false, false, !0),
425 Some(ref c) => (true, c.direct, !c.path_len),
428 if old_rank >= new_rank {
429 return; // no change needed
432 cmeta.extern_crate.set(Some(extern_crate));
433 // Propagate the extern crate info to dependencies.
434 extern_crate.direct = false;
435 for &dep_cnum in cmeta.cnum_map.borrow().iter() {
436 self.update_extern_crate(dep_cnum, extern_crate, visited);
440 // Go through the crate metadata and load any crates that it references
441 fn resolve_crate_deps(&mut self,
442 root: &Option<CratePaths>,
443 crate_root: &CrateRoot,
444 metadata: &MetadataBlob,
448 -> cstore::CrateNumMap {
449 debug!("resolving deps of external crate");
450 if crate_root.macro_derive_registrar.is_some() {
451 return cstore::CrateNumMap::new();
454 // The map from crate numbers in the crate we're resolving to local crate
456 let deps = crate_root.crate_deps.decode(metadata);
457 let map: FxHashMap<_, _> = deps.enumerate().map(|(crate_num, dep)| {
458 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
459 let dep_name = &dep.name.as_str();
460 let dep_kind = match dep_kind {
461 DepKind::MacrosOnly => DepKind::MacrosOnly,
464 let (local_cnum, ..) = self.resolve_crate(
465 root, dep_name, dep_name, Some(&dep.hash), span, PathKind::Dependency, dep_kind,
467 (CrateNum::new(crate_num + 1), local_cnum)
470 let max_cnum = map.values().cloned().max().map(|cnum| cnum.as_u32()).unwrap_or(0);
472 // we map 0 and all other holes in the map to our parent crate. The "additional"
473 // self-dependencies should be harmless.
474 (0..max_cnum+1).map(|cnum| {
475 map.get(&CrateNum::from_u32(cnum)).cloned().unwrap_or(krate)
479 fn read_extension_crate(&mut self, span: Span, info: &ExternCrateInfo) -> ExtensionCrate {
480 info!("read extension crate {} `extern crate {} as {}` dep_kind={:?}",
481 info.id, info.name, info.ident, info.dep_kind);
482 let target_triple = &self.sess.opts.target_triple[..];
483 let is_cross = target_triple != config::host_triple();
484 let mut target_only = false;
485 let ident = info.ident.clone();
486 let name = info.name.clone();
487 let mut locate_ctxt = locator::Context {
491 crate_name: &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 should_match_name: true,
504 let library = self.load(&mut locate_ctxt).or_else(|| {
508 // Try loading from target crates. This will abort later if we
509 // try to load a plugin registrar function,
512 locate_ctxt.target = &self.sess.target.target;
513 locate_ctxt.triple = target_triple;
514 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
516 self.load(&mut locate_ctxt)
518 let library = match library {
520 None => locate_ctxt.report_errs(),
523 let (dylib, metadata) = match library {
524 LoadResult::Previous(cnum) => {
525 let data = self.cstore.get_crate_data(cnum);
526 (data.source.dylib.clone(), PMDSource::Registered(data))
528 LoadResult::Loaded(library) => {
529 let dylib = library.dylib.clone();
530 let metadata = PMDSource::Owned(library);
537 dylib: dylib.map(|p| p.0),
538 target_only: target_only,
542 /// Load custom derive macros.
544 /// Note that this is intentionally similar to how we load plugins today,
545 /// but also intentionally separate. Plugins are likely always going to be
546 /// implemented as dynamic libraries, but we have a possible future where
547 /// custom derive (and other macro-1.1 style features) are implemented via
548 /// executables and custom IPC.
549 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
550 -> Vec<(ast::Name, Rc<SyntaxExtension>)> {
552 use proc_macro::TokenStream;
553 use proc_macro::__internal::Registry;
554 use rustc_back::dynamic_lib::DynamicLibrary;
555 use syntax_ext::deriving::custom::CustomDerive;
557 let path = match dylib {
558 Some(dylib) => dylib,
559 None => span_bug!(span, "proc-macro crate not dylib"),
561 // Make sure the path contains a / or the linker will search for it.
562 let path = env::current_dir().unwrap().join(path);
563 let lib = match DynamicLibrary::open(Some(&path)) {
565 Err(err) => self.sess.span_fatal(span, &err),
568 let sym = self.sess.generate_derive_registrar_symbol(&root.hash,
569 root.macro_derive_registrar.unwrap());
570 let registrar = unsafe {
571 let sym = match lib.symbol(&sym) {
573 Err(err) => self.sess.span_fatal(span, &err),
575 mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
578 struct MyRegistrar(Vec<(ast::Name, Rc<SyntaxExtension>)>);
580 impl Registry for MyRegistrar {
581 fn register_custom_derive(&mut self,
583 expand: fn(TokenStream) -> TokenStream,
584 attributes: &[&'static str]) {
585 let attrs = attributes.iter().map(|s| InternedString::new(s)).collect();
586 let derive = SyntaxExtension::CustomDerive(
587 Box::new(CustomDerive::new(expand, attrs))
589 self.0.push((intern(trait_name), Rc::new(derive)));
593 let mut my_registrar = MyRegistrar(Vec::new());
594 registrar(&mut my_registrar);
596 // Intentionally leak the dynamic library. We can't ever unload it
597 // since the library can make things that will live arbitrarily long.
602 /// Look for a plugin registrar. Returns library path, crate
603 /// SVH and DefIndex of the registrar function.
604 pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
605 -> Option<(PathBuf, Svh, DefIndex)> {
606 let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
607 name: name.to_string(),
608 ident: name.to_string(),
609 id: ast::DUMMY_NODE_ID,
610 dep_kind: DepKind::MacrosOnly,
613 if ekrate.target_only {
614 // Need to abort before syntax expansion.
615 let message = format!("plugin `{}` is not available for triple `{}` \
618 config::host_triple(),
619 self.sess.opts.target_triple);
620 span_fatal!(self.sess, span, E0456, "{}", &message[..]);
623 let root = ekrate.metadata.get_root();
624 match (ekrate.dylib.as_ref(), root.plugin_registrar_fn) {
625 (Some(dylib), Some(reg)) => {
626 Some((dylib.to_path_buf(), root.hash, reg))
629 span_err!(self.sess, span, E0457,
630 "plugin `{}` only found in rlib format, but must be available \
633 // No need to abort because the loading code will just ignore this
641 fn register_statically_included_foreign_items(&mut self) {
642 let libs = self.cstore.get_used_libraries();
643 for (foreign_lib, list) in self.foreign_item_map.iter() {
644 let is_static = libs.borrow().iter().any(|lib| {
645 *foreign_lib == lib.name && lib.kind == cstore::NativeStatic
649 self.cstore.add_statically_included_foreign_item(*id);
655 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
656 // If we're only compiling an rlib, then there's no need to select a
657 // panic runtime, so we just skip this section entirely.
658 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
659 *ct != config::CrateTypeRlib
662 info!("panic runtime injection skipped, only generating rlib");
666 // If we need a panic runtime, we try to find an existing one here. At
667 // the same time we perform some general validation of the DAG we've got
668 // going such as ensuring everything has a compatible panic strategy.
670 // The logic for finding the panic runtime here is pretty much the same
671 // as the allocator case with the only addition that the panic strategy
672 // compilation mode also comes into play.
673 let desired_strategy = self.sess.panic_strategy();
674 let mut runtime_found = false;
675 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
676 "needs_panic_runtime");
677 self.cstore.iter_crate_data(|cnum, data| {
678 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
679 if data.is_panic_runtime() {
680 // Inject a dependency from all #![needs_panic_runtime] to this
681 // #![panic_runtime] crate.
682 self.inject_dependency_if(cnum, "a panic runtime",
683 &|data| data.needs_panic_runtime());
684 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
688 // If an explicitly linked and matching panic runtime was found, or if
689 // we just don't need one at all, then we're done here and there's
690 // nothing else to do.
691 if !needs_panic_runtime || runtime_found {
695 // By this point we know that we (a) need a panic runtime and (b) no
696 // panic runtime was explicitly linked. Here we just load an appropriate
697 // default runtime for our panic strategy and then inject the
700 // We may resolve to an already loaded crate (as the crate may not have
701 // been explicitly linked prior to this) and we may re-inject
702 // dependencies again, but both of those situations are fine.
704 // Also note that we have yet to perform validation of the crate graph
705 // in terms of everyone has a compatible panic runtime format, that's
706 // performed later as part of the `dependency_format` module.
707 let name = match desired_strategy {
708 PanicStrategy::Unwind => "panic_unwind",
709 PanicStrategy::Abort => "panic_abort",
711 info!("panic runtime not found -- loading {}", name);
713 let dep_kind = DepKind::Implicit;
715 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
717 // Sanity check the loaded crate to ensure it is indeed a panic runtime
718 // and the panic strategy is indeed what we thought it was.
719 if !data.is_panic_runtime() {
720 self.sess.err(&format!("the crate `{}` is not a panic runtime",
723 if data.panic_strategy() != desired_strategy {
724 self.sess.err(&format!("the crate `{}` does not have the panic \
726 name, desired_strategy.desc()));
729 self.sess.injected_panic_runtime.set(Some(cnum));
730 self.inject_dependency_if(cnum, "a panic runtime",
731 &|data| data.needs_panic_runtime());
734 fn inject_allocator_crate(&mut self) {
735 // Make sure that we actually need an allocator, if none of our
736 // dependencies need one then we definitely don't!
738 // Also, if one of our dependencies has an explicit allocator, then we
739 // also bail out as we don't need to implicitly inject one.
740 let mut needs_allocator = false;
741 let mut found_required_allocator = false;
742 self.cstore.iter_crate_data(|cnum, data| {
743 needs_allocator = needs_allocator || data.needs_allocator();
744 if data.is_allocator() {
745 info!("{} required by rlib and is an allocator", data.name());
746 self.inject_dependency_if(cnum, "an allocator",
747 &|data| data.needs_allocator());
748 found_required_allocator = found_required_allocator ||
749 data.dep_kind.get() == DepKind::Explicit;
752 if !needs_allocator || found_required_allocator { return }
754 // At this point we've determined that we need an allocator and no
755 // previous allocator has been activated. We look through our outputs of
756 // crate types to see what kind of allocator types we may need.
758 // The main special output type here is that rlibs do **not** need an
759 // allocator linked in (they're just object files), only final products
760 // (exes, dylibs, staticlibs) need allocators.
761 let mut need_lib_alloc = false;
762 let mut need_exe_alloc = false;
763 for ct in self.sess.crate_types.borrow().iter() {
765 config::CrateTypeExecutable => need_exe_alloc = true,
766 config::CrateTypeDylib |
767 config::CrateTypeProcMacro |
768 config::CrateTypeCdylib |
769 config::CrateTypeStaticlib => need_lib_alloc = true,
770 config::CrateTypeRlib => {}
773 if !need_lib_alloc && !need_exe_alloc { return }
775 // The default allocator crate comes from the custom target spec, and we
776 // choose between the standard library allocator or exe allocator. This
777 // distinction exists because the default allocator for binaries (where
778 // the world is Rust) is different than library (where the world is
779 // likely *not* Rust).
781 // If a library is being produced, but we're also flagged with `-C
782 // prefer-dynamic`, then we interpret this as a *Rust* dynamic library
783 // is being produced so we use the exe allocator instead.
785 // What this boils down to is:
787 // * Binaries use jemalloc
788 // * Staticlibs and Rust dylibs use system malloc
789 // * Rust dylibs used as dependencies to rust use jemalloc
790 let name = if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
791 &self.sess.target.target.options.lib_allocation_crate
793 &self.sess.target.target.options.exe_allocation_crate
795 let dep_kind = DepKind::Implicit;
797 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
799 // Sanity check the crate we loaded to ensure that it is indeed an
801 if !data.is_allocator() {
802 self.sess.err(&format!("the allocator crate `{}` is not tagged \
803 with #![allocator]", data.name()));
806 self.sess.injected_allocator.set(Some(cnum));
807 self.inject_dependency_if(cnum, "an allocator",
808 &|data| data.needs_allocator());
811 fn inject_dependency_if(&self,
814 needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
815 // don't perform this validation if the session has errors, as one of
816 // those errors may indicate a circular dependency which could cause
817 // this to stack overflow.
818 if self.sess.has_errors() {
822 // Before we inject any dependencies, make sure we don't inject a
823 // circular dependency by validating that this crate doesn't
824 // transitively depend on any crates satisfying `needs_dep`.
825 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
826 let data = self.cstore.get_crate_data(dep);
827 if needs_dep(&data) {
828 self.sess.err(&format!("the crate `{}` cannot depend \
829 on a crate that needs {}, but \
831 self.cstore.get_crate_data(krate).name(),
837 // All crates satisfying `needs_dep` do not explicitly depend on the
838 // crate provided for this compile, but in order for this compilation to
839 // be successfully linked we need to inject a dependency (to order the
840 // crates on the command line correctly).
841 self.cstore.iter_crate_data(|cnum, data| {
842 if !needs_dep(data) {
846 info!("injecting a dep from {} to {}", cnum, krate);
847 data.cnum_map.borrow_mut().push(krate);
852 impl<'a> CrateLoader<'a> {
853 pub fn preprocess(&mut self, krate: &ast::Crate) {
854 for attr in krate.attrs.iter().filter(|m| m.name() == "link_args") {
855 if let Some(ref linkarg) = attr.value_str() {
856 self.cstore.add_used_link_args(&linkarg);
861 fn process_foreign_mod(&mut self, i: &ast::Item, fm: &ast::ForeignMod) {
862 if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
866 // First, add all of the custom #[link_args] attributes
867 for m in i.attrs.iter().filter(|a| a.check_name("link_args")) {
868 if let Some(linkarg) = m.value_str() {
869 self.cstore.add_used_link_args(&linkarg);
873 // Next, process all of the #[link(..)]-style arguments
874 for m in i.attrs.iter().filter(|a| a.check_name("link")) {
875 let items = match m.meta_item_list() {
879 let kind = items.iter().find(|k| {
881 }).and_then(|a| a.value_str());
882 let kind = match kind.as_ref().map(|s| &s[..]) {
883 Some("static") => cstore::NativeStatic,
884 Some("dylib") => cstore::NativeUnknown,
885 Some("framework") => cstore::NativeFramework,
887 struct_span_err!(self.sess, m.span, E0458,
888 "unknown kind: `{}`", k)
889 .span_label(m.span, &format!("unknown kind")).emit();
890 cstore::NativeUnknown
892 None => cstore::NativeUnknown
894 let n = items.iter().find(|n| {
896 }).and_then(|a| a.value_str());
900 struct_span_err!(self.sess, m.span, E0459,
901 "#[link(...)] specified without `name = \"foo\"`")
902 .span_label(m.span, &format!("missing `name` argument")).emit();
903 InternedString::new("foo")
906 let cfg = items.iter().find(|k| {
908 }).and_then(|a| a.meta_item_list());
909 let cfg = cfg.map(|list| {
910 list[0].meta_item().unwrap().clone()
912 let lib = NativeLibrary {
917 register_native_lib(self.sess, self.cstore, Some(m.span), lib);
920 // Finally, process the #[linked_from = "..."] attribute
921 for m in i.attrs.iter().filter(|a| a.check_name("linked_from")) {
922 let lib_name = match m.value_str() {
926 let list = self.foreign_item_map.entry(lib_name.to_string())
927 .or_insert(Vec::new());
928 list.extend(fm.items.iter().map(|it| it.id));
933 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
934 fn postprocess(&mut self, krate: &ast::Crate) {
935 self.inject_allocator_crate();
936 self.inject_panic_runtime(krate);
938 if log_enabled!(log::INFO) {
939 dump_crates(&self.cstore);
942 for &(ref name, kind) in &self.sess.opts.libs {
943 let lib = NativeLibrary {
948 register_native_lib(self.sess, self.cstore, None, lib);
950 self.register_statically_included_foreign_items();
953 fn process_item(&mut self, item: &ast::Item, definitions: &Definitions) {
955 ast::ItemKind::ExternCrate(_) => {}
956 ast::ItemKind::ForeignMod(ref fm) => return self.process_foreign_mod(item, fm),
960 let info = self.extract_crate_info(item).unwrap();
961 let (cnum, ..) = self.resolve_crate(
962 &None, &info.ident, &info.name, None, item.span, PathKind::Crate, info.dep_kind,
965 let def_id = definitions.opt_local_def_id(item.id).unwrap();
966 let len = definitions.def_path(def_id.index).data.len();
969 ExternCrate { def_id: def_id, span: item.span, direct: true, path_len: len };
970 self.update_extern_crate(cnum, extern_crate, &mut FxHashSet());
971 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);