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, Tracked};
17 use rustc::dep_graph::{DepNode, GlobalMetaDataKind};
18 use rustc::hir::def_id::{DefId, CrateNum, DefIndex, CRATE_DEF_INDEX};
19 use rustc::hir::svh::Svh;
20 use rustc::middle::cstore::DepKind;
21 use rustc::session::Session;
22 use rustc::session::config::{Sanitizer, self};
23 use rustc_back::PanicStrategy;
24 use rustc::session::search_paths::PathKind;
26 use rustc::middle::cstore::{CrateStore, validate_crate_name, ExternCrate};
27 use rustc::util::common::record_time;
28 use rustc::util::nodemap::FxHashSet;
29 use rustc::middle::cstore::NativeLibrary;
30 use rustc::hir::map::Definitions;
32 use std::cell::{RefCell, Cell};
34 use std::path::PathBuf;
41 use syntax::ext::base::SyntaxExtension;
42 use syntax::feature_gate::{self, GateIssue};
43 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 fn register_native_lib(sess: &Session,
87 if lib.name.as_str().is_empty() {
90 struct_span_err!(sess, span, E0454,
91 "#[link(name = \"\")] given with empty name")
92 .span_label(span, "empty name given")
96 sess.err("empty library name given via `-l`");
101 let is_osx = sess.target.target.options.is_like_osx;
102 if lib.kind == cstore::NativeFramework && !is_osx {
103 let msg = "native frameworks are only available on macOS targets";
105 Some(span) => span_err!(sess, span, E0455, "{}", msg),
106 None => sess.err(msg),
109 if lib.cfg.is_some() && !sess.features.borrow().link_cfg {
110 feature_gate::emit_feature_err(&sess.parse_sess,
116 if lib.kind == cstore::NativeStaticNobundle && !sess.features.borrow().static_nobundle {
117 feature_gate::emit_feature_err(&sess.parse_sess,
121 "kind=\"static-nobundle\" is feature gated");
123 cstore.add_used_library(lib);
126 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
128 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
133 // Extra info about a crate loaded for plugins or exported macros.
134 struct ExtensionCrate {
136 dylib: Option<PathBuf>,
141 Registered(Rc<cstore::CrateMetadata>),
145 impl Deref for PMDSource {
146 type Target = MetadataBlob;
148 fn deref(&self) -> &MetadataBlob {
150 PMDSource::Registered(ref cmd) => &cmd.blob,
151 PMDSource::Owned(ref lib) => &lib.metadata
161 impl<'a> CrateLoader<'a> {
162 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
166 next_crate_num: cstore.next_crate_num(),
167 local_crate_name: Symbol::intern(local_crate_name),
171 fn extract_crate_info(&self, i: &ast::Item) -> Option<ExternCrateInfo> {
173 ast::ItemKind::ExternCrate(ref path_opt) => {
174 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
176 let name = match *path_opt {
178 validate_crate_name(Some(self.sess), &name.as_str(),
182 None => i.ident.name,
184 Some(ExternCrateInfo {
188 dep_kind: if attr::contains_name(&i.attrs, "no_link") {
189 DepKind::UnexportedMacrosOnly
199 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
200 -> Option<CrateNum> {
202 self.cstore.iter_crate_data(|cnum, data| {
203 if data.name != name { return }
206 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
211 // When the hash is None we're dealing with a top-level dependency
212 // in which case we may have a specification on the command line for
213 // this library. Even though an upstream library may have loaded
214 // something of the same name, we have to make sure it was loaded
215 // from the exact same location as well.
217 // We're also sure to compare *paths*, not actual byte slices. The
218 // `source` stores paths which are normalized which may be different
219 // from the strings on the command line.
220 let source = self.cstore.used_crate_source(cnum);
221 if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
222 let found = locs.iter().any(|l| {
223 let l = fs::canonicalize(l).ok();
224 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
225 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
233 // Alright, so we've gotten this far which means that `data` has the
234 // right name, we don't have a hash, and we don't have a --extern
235 // pointing for ourselves. We're still not quite yet done because we
236 // have to make sure that this crate was found in the crate lookup
237 // path (this is a top-level dependency) as we don't want to
238 // implicitly load anything inside the dependency lookup path.
239 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
240 .or(source.rmeta.as_ref())
241 .expect("No sources for crate").1;
242 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
249 fn verify_no_symbol_conflicts(&self,
252 // Check for (potential) conflicts with the local crate
253 if self.local_crate_name == root.name &&
254 self.sess.local_crate_disambiguator() == root.disambiguator {
255 span_fatal!(self.sess, span, E0519,
256 "the current crate is indistinguishable from one of its \
257 dependencies: it has the same crate-name `{}` and was \
258 compiled with the same `-C metadata` arguments. This \
259 will result in symbol conflicts between the two.",
263 // Check for conflicts with any crate loaded so far
264 self.cstore.iter_crate_data(|_, other| {
265 if other.name() == root.name && // same crate-name
266 other.disambiguator() == root.disambiguator && // same crate-disambiguator
267 other.hash() != root.hash { // but different SVH
268 span_fatal!(self.sess, span, E0523,
269 "found two different crates with name `{}` that are \
270 not distinguished by differing `-C metadata`. This \
271 will result in symbol conflicts between the two.",
277 fn register_crate(&mut self,
278 root: &Option<CratePaths>,
284 -> (CrateNum, Rc<cstore::CrateMetadata>) {
285 info!("register crate `extern crate {} as {}`", name, ident);
286 let crate_root = lib.metadata.get_root();
287 self.verify_no_symbol_conflicts(span, &crate_root);
289 // Claim this crate number and cache it
290 let cnum = self.next_crate_num;
291 self.next_crate_num = CrateNum::from_u32(cnum.as_u32() + 1);
293 // Stash paths for top-most crate locally if necessary.
294 let crate_paths = if root.is_none() {
296 ident: ident.to_string(),
297 dylib: lib.dylib.clone().map(|p| p.0),
298 rlib: lib.rlib.clone().map(|p| p.0),
299 rmeta: lib.rmeta.clone().map(|p| p.0),
304 // Maintain a reference to the top most crate.
305 let root = if root.is_some() { root } else { &crate_paths };
307 let Library { dylib, rlib, rmeta, metadata } = lib;
309 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
311 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
312 crate_root.def_path_table.decode(&metadata)
315 let exported_symbols = crate_root.exported_symbols
316 .map(|x| x.decode(&metadata).collect());
318 let trait_impls = crate_root
321 impls.decode(&metadata)
322 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
326 let mut cmeta = cstore::CrateMetadata {
328 extern_crate: Cell::new(None),
329 def_path_table: def_path_table,
330 exported_symbols: exported_symbols,
331 trait_impls: trait_impls,
332 proc_macros: crate_root.macro_derive_registrar.map(|_| {
333 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
337 cnum_map: RefCell::new(cnum_map),
339 codemap_import_info: RefCell::new(vec![]),
340 attribute_cache: RefCell::new([Vec::new(), Vec::new()]),
341 dep_kind: Cell::new(dep_kind),
342 source: cstore::CrateSource {
347 // Initialize this with an empty set. The field is populated below
348 // after we were able to deserialize its contents.
349 dllimport_foreign_items: Tracked::new(FxHashSet()),
352 let dllimports: Tracked<FxHashSet<_>> = cmeta
355 .map(|native_libraries| {
356 let native_libraries: Vec<_> = native_libraries.decode(&cmeta)
360 .filter(|lib| relevant_lib(self.sess, lib) &&
361 lib.kind == cstore::NativeLibraryKind::NativeUnknown)
362 .flat_map(|lib| lib.foreign_items.iter())
367 cmeta.dllimport_foreign_items = dllimports;
369 let cmeta = Rc::new(cmeta);
370 self.cstore.set_crate_data(cnum, cmeta.clone());
374 fn resolve_crate(&mut self,
375 root: &Option<CratePaths>,
381 mut dep_kind: DepKind)
382 -> (CrateNum, Rc<cstore::CrateMetadata>) {
383 info!("resolving crate `extern crate {} as {}`", name, ident);
384 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
385 LoadResult::Previous(cnum)
387 info!("falling back to a load");
388 let mut locate_ctxt = locator::Context {
393 hash: hash.map(|a| &*a),
394 filesearch: self.sess.target_filesearch(path_kind),
395 target: &self.sess.target.target,
396 triple: &self.sess.opts.target_triple,
398 rejected_via_hash: vec![],
399 rejected_via_triple: vec![],
400 rejected_via_kind: vec![],
401 rejected_via_version: vec![],
402 rejected_via_filename: vec![],
403 should_match_name: true,
404 is_proc_macro: Some(false),
405 metadata_loader: &*self.cstore.metadata_loader,
408 self.load(&mut locate_ctxt).or_else(|| {
409 dep_kind = DepKind::UnexportedMacrosOnly;
411 let mut proc_macro_locator = locator::Context {
412 target: &self.sess.host,
413 triple: config::host_triple(),
414 filesearch: self.sess.host_filesearch(path_kind),
415 rejected_via_hash: vec![],
416 rejected_via_triple: vec![],
417 rejected_via_kind: vec![],
418 rejected_via_version: vec![],
419 rejected_via_filename: vec![],
420 is_proc_macro: Some(true),
424 self.load(&mut proc_macro_locator)
425 }).unwrap_or_else(|| locate_ctxt.report_errs())
429 LoadResult::Previous(cnum) => {
430 let data = self.cstore.get_crate_data(cnum);
431 if data.root.macro_derive_registrar.is_some() {
432 dep_kind = DepKind::UnexportedMacrosOnly;
434 data.dep_kind.set(cmp::max(data.dep_kind.get(), dep_kind));
437 LoadResult::Loaded(library) => {
438 self.register_crate(root, ident, name, span, library, dep_kind)
443 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
444 let library = match locate_ctxt.maybe_load_library_crate() {
449 // In the case that we're loading a crate, but not matching
450 // against a hash, we could load a crate which has the same hash
451 // as an already loaded crate. If this is the case prevent
452 // duplicates by just using the first crate.
454 // Note that we only do this for target triple crates, though, as we
455 // don't want to match a host crate against an equivalent target one
457 let root = library.metadata.get_root();
458 if locate_ctxt.triple == self.sess.opts.target_triple {
459 let mut result = LoadResult::Loaded(library);
460 self.cstore.iter_crate_data(|cnum, data| {
461 if data.name() == root.name && root.hash == data.hash() {
462 assert!(locate_ctxt.hash.is_none());
463 info!("load success, going to previous cnum: {}", cnum);
464 result = LoadResult::Previous(cnum);
469 Some(LoadResult::Loaded(library))
473 fn update_extern_crate(&mut self,
475 mut extern_crate: ExternCrate,
476 visited: &mut FxHashSet<(CrateNum, bool)>)
478 if !visited.insert((cnum, extern_crate.direct)) { return }
480 let cmeta = self.cstore.get_crate_data(cnum);
481 let old_extern_crate = cmeta.extern_crate.get();
484 // - something over nothing (tuple.0);
485 // - direct extern crate to indirect (tuple.1);
486 // - shorter paths to longer (tuple.2).
487 let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
488 let old_rank = match old_extern_crate {
489 None => (false, false, !0),
490 Some(ref c) => (true, c.direct, !c.path_len),
493 if old_rank >= new_rank {
494 return; // no change needed
497 cmeta.extern_crate.set(Some(extern_crate));
498 // Propagate the extern crate info to dependencies.
499 extern_crate.direct = false;
500 for &dep_cnum in cmeta.cnum_map.borrow().iter() {
501 self.update_extern_crate(dep_cnum, extern_crate, visited);
505 // Go through the crate metadata and load any crates that it references
506 fn resolve_crate_deps(&mut self,
507 root: &Option<CratePaths>,
508 crate_root: &CrateRoot,
509 metadata: &MetadataBlob,
513 -> cstore::CrateNumMap {
514 debug!("resolving deps of external crate");
515 if crate_root.macro_derive_registrar.is_some() {
516 return cstore::CrateNumMap::new();
519 let dep_node = DepNode::GlobalMetaData(DefId { krate, index: CRATE_DEF_INDEX },
520 GlobalMetaDataKind::CrateDeps);
522 // The map from crate numbers in the crate we're resolving to local crate numbers.
523 // We map 0 and all other holes in the map to our parent crate. The "additional"
524 // self-dependencies should be harmless.
525 ::std::iter::once(krate).chain(crate_root.crate_deps
526 .get(&self.sess.dep_graph, dep_node)
529 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
530 if dep.kind == DepKind::UnexportedMacrosOnly {
533 let dep_kind = match dep_kind {
534 DepKind::MacrosOnly => DepKind::MacrosOnly,
537 let (local_cnum, ..) = self.resolve_crate(
538 root, dep.name, dep.name, Some(&dep.hash), span, PathKind::Dependency, dep_kind,
544 fn read_extension_crate(&mut self, span: Span, info: &ExternCrateInfo) -> ExtensionCrate {
545 info!("read extension crate {} `extern crate {} as {}` dep_kind={:?}",
546 info.id, info.name, info.ident, info.dep_kind);
547 let target_triple = &self.sess.opts.target_triple[..];
548 let is_cross = target_triple != config::host_triple();
549 let mut target_only = false;
550 let mut locate_ctxt = locator::Context {
554 crate_name: info.name,
556 filesearch: self.sess.host_filesearch(PathKind::Crate),
557 target: &self.sess.host,
558 triple: config::host_triple(),
560 rejected_via_hash: vec![],
561 rejected_via_triple: vec![],
562 rejected_via_kind: vec![],
563 rejected_via_version: vec![],
564 rejected_via_filename: vec![],
565 should_match_name: true,
567 metadata_loader: &*self.cstore.metadata_loader,
569 let library = self.load(&mut locate_ctxt).or_else(|| {
573 // Try loading from target crates. This will abort later if we
574 // try to load a plugin registrar function,
577 locate_ctxt.target = &self.sess.target.target;
578 locate_ctxt.triple = target_triple;
579 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
581 self.load(&mut locate_ctxt)
583 let library = match library {
585 None => locate_ctxt.report_errs(),
588 let (dylib, metadata) = match library {
589 LoadResult::Previous(cnum) => {
590 let data = self.cstore.get_crate_data(cnum);
591 (data.source.dylib.clone(), PMDSource::Registered(data))
593 LoadResult::Loaded(library) => {
594 let dylib = library.dylib.clone();
595 let metadata = PMDSource::Owned(library);
602 dylib: dylib.map(|p| p.0),
603 target_only: target_only,
607 /// Load custom derive macros.
609 /// Note that this is intentionally similar to how we load plugins today,
610 /// but also intentionally separate. Plugins are likely always going to be
611 /// implemented as dynamic libraries, but we have a possible future where
612 /// custom derive (and other macro-1.1 style features) are implemented via
613 /// executables and custom IPC.
614 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
615 -> Vec<(ast::Name, Rc<SyntaxExtension>)> {
617 use proc_macro::TokenStream;
618 use proc_macro::__internal::Registry;
619 use rustc_back::dynamic_lib::DynamicLibrary;
620 use syntax_ext::deriving::custom::ProcMacroDerive;
621 use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
623 let path = match dylib {
624 Some(dylib) => dylib,
625 None => span_bug!(span, "proc-macro crate not dylib"),
627 // Make sure the path contains a / or the linker will search for it.
628 let path = env::current_dir().unwrap().join(path);
629 let lib = match DynamicLibrary::open(Some(&path)) {
631 Err(err) => self.sess.span_fatal(span, &err),
634 let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator,
635 root.macro_derive_registrar.unwrap());
636 let registrar = unsafe {
637 let sym = match lib.symbol(&sym) {
639 Err(err) => self.sess.span_fatal(span, &err),
641 mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
644 struct MyRegistrar(Vec<(ast::Name, Rc<SyntaxExtension>)>);
646 impl Registry for MyRegistrar {
647 fn register_custom_derive(&mut self,
649 expand: fn(TokenStream) -> TokenStream,
650 attributes: &[&'static str]) {
651 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
652 let derive = ProcMacroDerive::new(expand, attrs.clone());
653 let derive = SyntaxExtension::ProcMacroDerive(Box::new(derive), attrs);
654 self.0.push((Symbol::intern(trait_name), Rc::new(derive)));
657 fn register_attr_proc_macro(&mut self,
659 expand: fn(TokenStream, TokenStream) -> TokenStream) {
660 let expand = SyntaxExtension::AttrProcMacro(
661 Box::new(AttrProcMacro { inner: expand })
663 self.0.push((Symbol::intern(name), Rc::new(expand)));
666 fn register_bang_proc_macro(&mut self,
668 expand: fn(TokenStream) -> TokenStream) {
669 let expand = SyntaxExtension::ProcMacro(
670 Box::new(BangProcMacro { inner: expand })
672 self.0.push((Symbol::intern(name), Rc::new(expand)));
676 let mut my_registrar = MyRegistrar(Vec::new());
677 registrar(&mut my_registrar);
679 // Intentionally leak the dynamic library. We can't ever unload it
680 // since the library can make things that will live arbitrarily long.
685 /// Look for a plugin registrar. Returns library path, crate
686 /// SVH and DefIndex of the registrar function.
687 pub fn find_plugin_registrar(&mut self,
690 -> Option<(PathBuf, Symbol, DefIndex)> {
691 let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
692 name: Symbol::intern(name),
693 ident: Symbol::intern(name),
694 id: ast::DUMMY_NODE_ID,
695 dep_kind: DepKind::UnexportedMacrosOnly,
698 if ekrate.target_only {
699 // Need to abort before syntax expansion.
700 let message = format!("plugin `{}` is not available for triple `{}` \
703 config::host_triple(),
704 self.sess.opts.target_triple);
705 span_fatal!(self.sess, span, E0456, "{}", &message);
708 let root = ekrate.metadata.get_root();
709 match (ekrate.dylib.as_ref(), root.plugin_registrar_fn) {
710 (Some(dylib), Some(reg)) => {
711 Some((dylib.to_path_buf(), root.disambiguator, reg))
714 span_err!(self.sess, span, E0457,
715 "plugin `{}` only found in rlib format, but must be available \
718 // No need to abort because the loading code will just ignore this
726 fn get_foreign_items_of_kind(&self, kind: cstore::NativeLibraryKind) -> Vec<DefIndex> {
727 let mut items = vec![];
728 let libs = self.cstore.get_used_libraries();
729 for lib in libs.borrow().iter() {
730 if relevant_lib(self.sess, lib) && lib.kind == kind {
731 items.extend(&lib.foreign_items);
737 fn register_statically_included_foreign_items(&mut self) {
738 for id in self.get_foreign_items_of_kind(cstore::NativeStatic) {
739 self.cstore.add_statically_included_foreign_item(id);
741 for id in self.get_foreign_items_of_kind(cstore::NativeStaticNobundle) {
742 self.cstore.add_statically_included_foreign_item(id);
746 fn register_dllimport_foreign_items(&mut self) {
747 let mut dllimports = self.cstore.dllimport_foreign_items.borrow_mut();
748 for id in self.get_foreign_items_of_kind(cstore::NativeUnknown) {
749 dllimports.insert(id);
753 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
754 // If we're only compiling an rlib, then there's no need to select a
755 // panic runtime, so we just skip this section entirely.
756 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
757 *ct != config::CrateTypeRlib
760 info!("panic runtime injection skipped, only generating rlib");
764 // If we need a panic runtime, we try to find an existing one here. At
765 // the same time we perform some general validation of the DAG we've got
766 // going such as ensuring everything has a compatible panic strategy.
768 // The logic for finding the panic runtime here is pretty much the same
769 // as the allocator case with the only addition that the panic strategy
770 // compilation mode also comes into play.
771 let desired_strategy = self.sess.panic_strategy();
772 let mut runtime_found = false;
773 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
774 "needs_panic_runtime");
776 let dep_graph = &self.sess.dep_graph;
778 self.cstore.iter_crate_data(|cnum, data| {
779 needs_panic_runtime = needs_panic_runtime ||
780 data.needs_panic_runtime(dep_graph);
781 if data.is_panic_runtime(dep_graph) {
782 // Inject a dependency from all #![needs_panic_runtime] to this
783 // #![panic_runtime] crate.
784 self.inject_dependency_if(cnum, "a panic runtime",
785 &|data| data.needs_panic_runtime(dep_graph));
786 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
790 // If an explicitly linked and matching panic runtime was found, or if
791 // we just don't need one at all, then we're done here and there's
792 // nothing else to do.
793 if !needs_panic_runtime || runtime_found {
797 // By this point we know that we (a) need a panic runtime and (b) no
798 // panic runtime was explicitly linked. Here we just load an appropriate
799 // default runtime for our panic strategy and then inject the
802 // We may resolve to an already loaded crate (as the crate may not have
803 // been explicitly linked prior to this) and we may re-inject
804 // dependencies again, but both of those situations are fine.
806 // Also note that we have yet to perform validation of the crate graph
807 // in terms of everyone has a compatible panic runtime format, that's
808 // performed later as part of the `dependency_format` module.
809 let name = match desired_strategy {
810 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
811 PanicStrategy::Abort => Symbol::intern("panic_abort"),
813 info!("panic runtime not found -- loading {}", name);
815 let dep_kind = DepKind::Implicit;
817 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
819 // Sanity check the loaded crate to ensure it is indeed a panic runtime
820 // and the panic strategy is indeed what we thought it was.
821 if !data.is_panic_runtime(dep_graph) {
822 self.sess.err(&format!("the crate `{}` is not a panic runtime",
825 if data.panic_strategy(dep_graph) != desired_strategy {
826 self.sess.err(&format!("the crate `{}` does not have the panic \
828 name, desired_strategy.desc()));
831 self.sess.injected_panic_runtime.set(Some(cnum));
832 self.inject_dependency_if(cnum, "a panic runtime",
833 &|data| data.needs_panic_runtime(dep_graph));
836 fn inject_sanitizer_runtime(&mut self) {
837 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
838 // Sanitizers can only be used on some tested platforms with
839 // executables linked to `std`
840 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
841 "x86_64-apple-darwin"];
842 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
843 "x86_64-apple-darwin"];
844 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
845 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
847 let supported_targets = match *sanitizer {
848 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
849 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
850 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
851 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
853 if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
854 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
856 supported_targets.join("` or `")
861 if !self.sess.crate_types.borrow().iter().all(|ct| {
864 config::CrateTypeExecutable => true,
865 // This crate will be compiled with the required
866 // instrumentation pass
867 config::CrateTypeRlib => false,
869 self.sess.err(&format!("Only executables and rlibs can be \
870 compiled with `-Z sanitizer`"));
878 let mut uses_std = false;
879 self.cstore.iter_crate_data(|_, data| {
880 if data.name == "std" {
886 let name = match *sanitizer {
887 Sanitizer::Address => "rustc_asan",
888 Sanitizer::Leak => "rustc_lsan",
889 Sanitizer::Memory => "rustc_msan",
890 Sanitizer::Thread => "rustc_tsan",
892 info!("loading sanitizer: {}", name);
894 let symbol = Symbol::intern(name);
895 let dep_kind = DepKind::Implicit;
897 self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
898 PathKind::Crate, dep_kind);
900 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
901 if !data.is_sanitizer_runtime(&self.sess.dep_graph) {
902 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
909 fn inject_allocator_crate(&mut self) {
910 // Make sure that we actually need an allocator, if none of our
911 // dependencies need one then we definitely don't!
913 // Also, if one of our dependencies has an explicit allocator, then we
914 // also bail out as we don't need to implicitly inject one.
915 let mut needs_allocator = false;
916 let mut found_required_allocator = false;
917 let dep_graph = &self.sess.dep_graph;
918 self.cstore.iter_crate_data(|cnum, data| {
919 needs_allocator = needs_allocator || data.needs_allocator(dep_graph);
920 if data.is_allocator(dep_graph) {
921 info!("{} required by rlib and is an allocator", data.name());
922 self.inject_dependency_if(cnum, "an allocator",
923 &|data| data.needs_allocator(dep_graph));
924 found_required_allocator = found_required_allocator ||
925 data.dep_kind.get() == DepKind::Explicit;
928 if !needs_allocator || found_required_allocator { return }
930 // At this point we've determined that we need an allocator and no
931 // previous allocator has been activated. We look through our outputs of
932 // crate types to see what kind of allocator types we may need.
934 // The main special output type here is that rlibs do **not** need an
935 // allocator linked in (they're just object files), only final products
936 // (exes, dylibs, staticlibs) need allocators.
937 let mut need_lib_alloc = false;
938 let mut need_exe_alloc = false;
939 for ct in self.sess.crate_types.borrow().iter() {
941 config::CrateTypeExecutable => need_exe_alloc = true,
942 config::CrateTypeDylib |
943 config::CrateTypeProcMacro |
944 config::CrateTypeCdylib |
945 config::CrateTypeStaticlib => need_lib_alloc = true,
946 config::CrateTypeRlib => {}
949 if !need_lib_alloc && !need_exe_alloc { return }
951 // The default allocator crate comes from the custom target spec, and we
952 // choose between the standard library allocator or exe allocator. This
953 // distinction exists because the default allocator for binaries (where
954 // the world is Rust) is different than library (where the world is
955 // likely *not* Rust).
957 // If a library is being produced, but we're also flagged with `-C
958 // prefer-dynamic`, then we interpret this as a *Rust* dynamic library
959 // is being produced so we use the exe allocator instead.
961 // What this boils down to is:
963 // * Binaries use jemalloc
964 // * Staticlibs and Rust dylibs use system malloc
965 // * Rust dylibs used as dependencies to rust use jemalloc
966 let name = if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
967 Symbol::intern(&self.sess.target.target.options.lib_allocation_crate)
969 Symbol::intern(&self.sess.target.target.options.exe_allocation_crate)
971 let dep_kind = DepKind::Implicit;
973 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
975 // Sanity check the crate we loaded to ensure that it is indeed an
977 if !data.is_allocator(dep_graph) {
978 self.sess.err(&format!("the allocator crate `{}` is not tagged \
979 with #![allocator]", data.name()));
982 self.sess.injected_allocator.set(Some(cnum));
983 self.inject_dependency_if(cnum, "an allocator",
984 &|data| data.needs_allocator(dep_graph));
987 fn inject_dependency_if(&self,
990 needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
991 // don't perform this validation if the session has errors, as one of
992 // those errors may indicate a circular dependency which could cause
993 // this to stack overflow.
994 if self.sess.has_errors() {
998 // Before we inject any dependencies, make sure we don't inject a
999 // circular dependency by validating that this crate doesn't
1000 // transitively depend on any crates satisfying `needs_dep`.
1001 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
1002 let data = self.cstore.get_crate_data(dep);
1003 if needs_dep(&data) {
1004 self.sess.err(&format!("the crate `{}` cannot depend \
1005 on a crate that needs {}, but \
1006 it depends on `{}`",
1007 self.cstore.get_crate_data(krate).name(),
1013 // All crates satisfying `needs_dep` do not explicitly depend on the
1014 // crate provided for this compile, but in order for this compilation to
1015 // be successfully linked we need to inject a dependency (to order the
1016 // crates on the command line correctly).
1017 self.cstore.iter_crate_data(|cnum, data| {
1018 if !needs_dep(data) {
1022 info!("injecting a dep from {} to {}", cnum, krate);
1023 data.cnum_map.borrow_mut().push(krate);
1028 impl<'a> CrateLoader<'a> {
1029 pub fn preprocess(&mut self, krate: &ast::Crate) {
1030 for attr in &krate.attrs {
1031 if attr.path == "link_args" {
1032 if let Some(linkarg) = attr.value_str() {
1033 self.cstore.add_used_link_args(&linkarg.as_str());
1039 fn process_foreign_mod(&mut self, i: &ast::Item, fm: &ast::ForeignMod,
1040 definitions: &Definitions) {
1041 if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
1045 // First, add all of the custom #[link_args] attributes
1046 for m in i.attrs.iter().filter(|a| a.check_name("link_args")) {
1047 if let Some(linkarg) = m.value_str() {
1048 self.cstore.add_used_link_args(&linkarg.as_str());
1052 // Next, process all of the #[link(..)]-style arguments
1053 for m in i.attrs.iter().filter(|a| a.check_name("link")) {
1054 let items = match m.meta_item_list() {
1058 let kind = items.iter().find(|k| {
1059 k.check_name("kind")
1060 }).and_then(|a| a.value_str()).map(Symbol::as_str);
1061 let kind = match kind.as_ref().map(|s| &s[..]) {
1062 Some("static") => cstore::NativeStatic,
1063 Some("static-nobundle") => cstore::NativeStaticNobundle,
1064 Some("dylib") => cstore::NativeUnknown,
1065 Some("framework") => cstore::NativeFramework,
1067 struct_span_err!(self.sess, m.span, E0458,
1068 "unknown kind: `{}`", k)
1069 .span_label(m.span, "unknown kind").emit();
1070 cstore::NativeUnknown
1072 None => cstore::NativeUnknown
1074 let n = items.iter().find(|n| {
1075 n.check_name("name")
1076 }).and_then(|a| a.value_str());
1080 struct_span_err!(self.sess, m.span, E0459,
1081 "#[link(...)] specified without `name = \"foo\"`")
1082 .span_label(m.span, "missing `name` argument").emit();
1083 Symbol::intern("foo")
1086 let cfg = items.iter().find(|k| {
1088 }).and_then(|a| a.meta_item_list());
1089 let cfg = cfg.map(|list| {
1090 list[0].meta_item().unwrap().clone()
1092 let foreign_items = fm.items.iter()
1093 .map(|it| definitions.opt_def_index(it.id).unwrap())
1095 let lib = NativeLibrary {
1099 foreign_items: foreign_items,
1101 register_native_lib(self.sess, self.cstore, Some(m.span), lib);
1106 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
1107 fn postprocess(&mut self, krate: &ast::Crate) {
1108 // inject the sanitizer runtime before the allocator runtime because all
1109 // sanitizers force the use of the `alloc_system` allocator
1110 self.inject_sanitizer_runtime();
1111 self.inject_allocator_crate();
1112 self.inject_panic_runtime(krate);
1114 if log_enabled!(log::LogLevel::Info) {
1115 dump_crates(&self.cstore);
1118 // Process libs passed on the command line
1119 // First, check for errors
1120 let mut renames = FxHashSet();
1121 for &(ref name, ref new_name, _) in &self.sess.opts.libs {
1122 if let &Some(ref new_name) = new_name {
1123 if new_name.is_empty() {
1125 &format!("an empty renaming target was specified for library `{}`",name));
1126 } else if !self.cstore.get_used_libraries().borrow().iter()
1127 .any(|lib| lib.name == name as &str) {
1128 self.sess.err(&format!("renaming of the library `{}` was specified, \
1129 however this crate contains no #[link(...)] \
1130 attributes referencing this library.", name));
1131 } else if renames.contains(name) {
1132 self.sess.err(&format!("multiple renamings were specified for library `{}` .",
1135 renames.insert(name);
1139 // Update kind and, optionally, the name of all native libaries
1140 // (there may be more than one) with the specified name.
1141 for &(ref name, ref new_name, kind) in &self.sess.opts.libs {
1142 let mut found = false;
1143 for lib in self.cstore.get_used_libraries().borrow_mut().iter_mut() {
1144 if lib.name == name as &str {
1145 let mut changed = false;
1146 if let Some(k) = kind {
1150 if let &Some(ref new_name) = new_name {
1151 lib.name = Symbol::intern(new_name);
1155 self.sess.warn(&format!("redundant linker flag specified for library `{}`",
1164 let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
1165 let lib = NativeLibrary {
1166 name: Symbol::intern(new_name.unwrap_or(name)),
1167 kind: if let Some(k) = kind { k } else { cstore::NativeUnknown },
1169 foreign_items: Vec::new(),
1171 register_native_lib(self.sess, self.cstore, None, lib);
1174 self.register_statically_included_foreign_items();
1175 self.register_dllimport_foreign_items();
1178 fn process_item(&mut self, item: &ast::Item, definitions: &Definitions) {
1180 ast::ItemKind::ForeignMod(ref fm) => {
1181 self.process_foreign_mod(item, fm, definitions)
1183 ast::ItemKind::ExternCrate(_) => {
1184 let info = self.extract_crate_info(item).unwrap();
1185 let (cnum, ..) = self.resolve_crate(
1186 &None, info.ident, info.name, None, item.span, PathKind::Crate, info.dep_kind,
1189 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1190 let len = definitions.def_path(def_id.index).data.len();
1193 ExternCrate { def_id: def_id, span: item.span, direct: true, path_len: len };
1194 self.update_extern_crate(cnum, extern_crate, &mut FxHashSet());
1195 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);