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::Session;
21 use rustc::session::config::{Sanitizer, self};
22 use rustc_back::PanicStrategy;
23 use rustc::session::search_paths::PathKind;
25 use rustc::middle::cstore::{CrateStore, validate_crate_name, ExternCrate};
26 use rustc::util::common::record_time;
27 use rustc::util::nodemap::FxHashSet;
28 use rustc::middle::cstore::NativeLibrary;
29 use rustc::hir::map::Definitions;
31 use std::cell::{RefCell, Cell};
33 use std::path::PathBuf;
40 use syntax::ext::base::SyntaxExtension;
41 use syntax::feature_gate::{self, GateIssue};
42 use syntax::symbol::Symbol;
43 use syntax_pos::{Span, DUMMY_SP};
47 pub dylib: Option<(PathBuf, PathKind)>,
48 pub rlib: Option<(PathBuf, PathKind)>,
49 pub rmeta: Option<(PathBuf, PathKind)>,
50 pub metadata: MetadataBlob,
53 pub struct CrateLoader<'a> {
54 pub sess: &'a Session,
56 next_crate_num: CrateNum,
57 local_crate_name: Symbol,
60 fn dump_crates(cstore: &CStore) {
61 info!("resolved crates:");
62 cstore.iter_crate_data(|_, data| {
63 info!(" name: {}", data.name());
64 info!(" cnum: {}", data.cnum);
65 info!(" hash: {}", data.hash());
66 info!(" reqd: {:?}", data.dep_kind.get());
67 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
68 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
69 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
70 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
75 struct ExternCrateInfo {
82 fn register_native_lib(sess: &Session,
86 if lib.name.as_str().is_empty() {
89 struct_span_err!(sess, span, E0454,
90 "#[link(name = \"\")] given with empty name")
91 .span_label(span, &format!("empty name given"))
95 sess.err("empty library name given via `-l`");
100 let is_osx = sess.target.target.options.is_like_osx;
101 if lib.kind == cstore::NativeFramework && !is_osx {
102 let msg = "native frameworks are only available on macOS targets";
104 Some(span) => span_err!(sess, span, E0455, "{}", msg),
105 None => sess.err(msg),
108 if lib.cfg.is_some() && !sess.features.borrow().link_cfg {
109 feature_gate::emit_feature_err(&sess.parse_sess,
115 if lib.kind == cstore::NativeStaticNobundle && !sess.features.borrow().static_nobundle {
116 feature_gate::emit_feature_err(&sess.parse_sess,
120 "kind=\"static-nobundle\" is feature gated");
122 cstore.add_used_library(lib);
125 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
127 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
132 // Extra info about a crate loaded for plugins or exported macros.
133 struct ExtensionCrate {
135 dylib: Option<PathBuf>,
140 Registered(Rc<cstore::CrateMetadata>),
144 impl Deref for PMDSource {
145 type Target = MetadataBlob;
147 fn deref(&self) -> &MetadataBlob {
149 PMDSource::Registered(ref cmd) => &cmd.blob,
150 PMDSource::Owned(ref lib) => &lib.metadata
160 impl<'a> CrateLoader<'a> {
161 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
165 next_crate_num: cstore.next_crate_num(),
166 local_crate_name: Symbol::intern(local_crate_name),
170 fn extract_crate_info(&self, i: &ast::Item) -> Option<ExternCrateInfo> {
172 ast::ItemKind::ExternCrate(ref path_opt) => {
173 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
175 let name = match *path_opt {
177 validate_crate_name(Some(self.sess), &name.as_str(),
181 None => i.ident.name,
183 Some(ExternCrateInfo {
187 dep_kind: if attr::contains_name(&i.attrs, "no_link") {
188 DepKind::UnexportedMacrosOnly
198 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
199 -> Option<CrateNum> {
201 self.cstore.iter_crate_data(|cnum, data| {
202 if data.name != name { return }
205 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
210 // When the hash is None we're dealing with a top-level dependency
211 // in which case we may have a specification on the command line for
212 // this library. Even though an upstream library may have loaded
213 // something of the same name, we have to make sure it was loaded
214 // from the exact same location as well.
216 // We're also sure to compare *paths*, not actual byte slices. The
217 // `source` stores paths which are normalized which may be different
218 // from the strings on the command line.
219 let source = self.cstore.used_crate_source(cnum);
220 if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
221 let found = locs.iter().any(|l| {
222 let l = fs::canonicalize(l).ok();
223 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
224 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
232 // Alright, so we've gotten this far which means that `data` has the
233 // right name, we don't have a hash, and we don't have a --extern
234 // pointing for ourselves. We're still not quite yet done because we
235 // have to make sure that this crate was found in the crate lookup
236 // path (this is a top-level dependency) as we don't want to
237 // implicitly load anything inside the dependency lookup path.
238 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
239 .or(source.rmeta.as_ref())
240 .expect("No sources for crate").1;
241 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
248 fn verify_no_symbol_conflicts(&self,
251 // Check for (potential) conflicts with the local crate
252 if self.local_crate_name == root.name &&
253 self.sess.local_crate_disambiguator() == root.disambiguator {
254 span_fatal!(self.sess, span, E0519,
255 "the current crate is indistinguishable from one of its \
256 dependencies: it has the same crate-name `{}` and was \
257 compiled with the same `-C metadata` arguments. This \
258 will result in symbol conflicts between the two.",
262 // Check for conflicts with any crate loaded so far
263 self.cstore.iter_crate_data(|_, other| {
264 if other.name() == root.name && // same crate-name
265 other.disambiguator() == root.disambiguator && // same crate-disambiguator
266 other.hash() != root.hash { // but different SVH
267 span_fatal!(self.sess, span, E0523,
268 "found two different crates with name `{}` that are \
269 not distinguished by differing `-C metadata`. This \
270 will result in symbol conflicts between the two.",
276 fn register_crate(&mut self,
277 root: &Option<CratePaths>,
283 -> (CrateNum, Rc<cstore::CrateMetadata>) {
284 info!("register crate `extern crate {} as {}`", name, ident);
285 let crate_root = lib.metadata.get_root();
286 self.verify_no_symbol_conflicts(span, &crate_root);
288 // Claim this crate number and cache it
289 let cnum = self.next_crate_num;
290 self.next_crate_num = CrateNum::from_u32(cnum.as_u32() + 1);
292 // Stash paths for top-most crate locally if necessary.
293 let crate_paths = if root.is_none() {
295 ident: ident.to_string(),
296 dylib: lib.dylib.clone().map(|p| p.0),
297 rlib: lib.rlib.clone().map(|p| p.0),
298 rmeta: lib.rmeta.clone().map(|p| p.0),
303 // Maintain a reference to the top most crate.
304 let root = if root.is_some() { root } else { &crate_paths };
306 let Library { dylib, rlib, rmeta, metadata } = lib;
308 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
310 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
311 crate_root.def_path_table.decode(&metadata)
314 let exported_symbols = crate_root.exported_symbols.decode(&metadata).collect();
316 let mut cmeta = cstore::CrateMetadata {
318 extern_crate: Cell::new(None),
319 def_path_table: def_path_table,
320 exported_symbols: exported_symbols,
321 proc_macros: crate_root.macro_derive_registrar.map(|_| {
322 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
326 cnum_map: RefCell::new(cnum_map),
328 codemap_import_info: RefCell::new(vec![]),
329 dep_kind: Cell::new(dep_kind),
330 source: cstore::CrateSource {
335 dllimport_foreign_items: FxHashSet(),
338 let dllimports: Vec<_> = cmeta.get_native_libraries().iter()
339 .filter(|lib| relevant_lib(self.sess, lib) &&
340 lib.kind == cstore::NativeLibraryKind::NativeUnknown)
341 .flat_map(|lib| &lib.foreign_items)
344 cmeta.dllimport_foreign_items.extend(dllimports);
346 let cmeta = Rc::new(cmeta);
347 self.cstore.set_crate_data(cnum, cmeta.clone());
351 fn resolve_crate(&mut self,
352 root: &Option<CratePaths>,
358 mut dep_kind: DepKind)
359 -> (CrateNum, Rc<cstore::CrateMetadata>) {
360 info!("resolving crate `extern crate {} as {}`", name, ident);
361 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
362 LoadResult::Previous(cnum)
364 info!("falling back to a load");
365 let mut locate_ctxt = locator::Context {
370 hash: hash.map(|a| &*a),
371 filesearch: self.sess.target_filesearch(path_kind),
372 target: &self.sess.target.target,
373 triple: &self.sess.opts.target_triple,
375 rejected_via_hash: vec![],
376 rejected_via_triple: vec![],
377 rejected_via_kind: vec![],
378 rejected_via_version: vec![],
379 rejected_via_filename: vec![],
380 should_match_name: true,
381 is_proc_macro: Some(false),
384 self.load(&mut locate_ctxt).or_else(|| {
385 dep_kind = DepKind::UnexportedMacrosOnly;
387 let mut proc_macro_locator = locator::Context {
388 target: &self.sess.host,
389 triple: config::host_triple(),
390 filesearch: self.sess.host_filesearch(path_kind),
391 rejected_via_hash: vec![],
392 rejected_via_triple: vec![],
393 rejected_via_kind: vec![],
394 rejected_via_version: vec![],
395 rejected_via_filename: vec![],
396 is_proc_macro: Some(true),
400 self.load(&mut proc_macro_locator)
401 }).unwrap_or_else(|| locate_ctxt.report_errs())
405 LoadResult::Previous(cnum) => {
406 let data = self.cstore.get_crate_data(cnum);
407 if data.root.macro_derive_registrar.is_some() {
408 dep_kind = DepKind::UnexportedMacrosOnly;
410 data.dep_kind.set(cmp::max(data.dep_kind.get(), dep_kind));
413 LoadResult::Loaded(library) => {
414 self.register_crate(root, ident, name, span, library, dep_kind)
419 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
420 let library = match locate_ctxt.maybe_load_library_crate() {
425 // In the case that we're loading a crate, but not matching
426 // against a hash, we could load a crate which has the same hash
427 // as an already loaded crate. If this is the case prevent
428 // duplicates by just using the first crate.
430 // Note that we only do this for target triple crates, though, as we
431 // don't want to match a host crate against an equivalent target one
433 let root = library.metadata.get_root();
434 if locate_ctxt.triple == self.sess.opts.target_triple {
435 let mut result = LoadResult::Loaded(library);
436 self.cstore.iter_crate_data(|cnum, data| {
437 if data.name() == root.name && root.hash == data.hash() {
438 assert!(locate_ctxt.hash.is_none());
439 info!("load success, going to previous cnum: {}", cnum);
440 result = LoadResult::Previous(cnum);
445 Some(LoadResult::Loaded(library))
449 fn update_extern_crate(&mut self,
451 mut extern_crate: ExternCrate,
452 visited: &mut FxHashSet<(CrateNum, bool)>)
454 if !visited.insert((cnum, extern_crate.direct)) { return }
456 let cmeta = self.cstore.get_crate_data(cnum);
457 let old_extern_crate = cmeta.extern_crate.get();
460 // - something over nothing (tuple.0);
461 // - direct extern crate to indirect (tuple.1);
462 // - shorter paths to longer (tuple.2).
463 let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
464 let old_rank = match old_extern_crate {
465 None => (false, false, !0),
466 Some(ref c) => (true, c.direct, !c.path_len),
469 if old_rank >= new_rank {
470 return; // no change needed
473 cmeta.extern_crate.set(Some(extern_crate));
474 // Propagate the extern crate info to dependencies.
475 extern_crate.direct = false;
476 for &dep_cnum in cmeta.cnum_map.borrow().iter() {
477 self.update_extern_crate(dep_cnum, extern_crate, visited);
481 // Go through the crate metadata and load any crates that it references
482 fn resolve_crate_deps(&mut self,
483 root: &Option<CratePaths>,
484 crate_root: &CrateRoot,
485 metadata: &MetadataBlob,
489 -> cstore::CrateNumMap {
490 debug!("resolving deps of external crate");
491 if crate_root.macro_derive_registrar.is_some() {
492 return cstore::CrateNumMap::new();
495 // The map from crate numbers in the crate we're resolving to local crate numbers.
496 // We map 0 and all other holes in the map to our parent crate. The "additional"
497 // self-dependencies should be harmless.
498 ::std::iter::once(krate).chain(crate_root.crate_deps.decode(metadata).map(|dep| {
499 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
500 if dep.kind == DepKind::UnexportedMacrosOnly {
503 let dep_kind = match dep_kind {
504 DepKind::MacrosOnly => DepKind::MacrosOnly,
507 let (local_cnum, ..) = self.resolve_crate(
508 root, dep.name, dep.name, Some(&dep.hash), span, PathKind::Dependency, dep_kind,
514 fn read_extension_crate(&mut self, span: Span, info: &ExternCrateInfo) -> ExtensionCrate {
515 info!("read extension crate {} `extern crate {} as {}` dep_kind={:?}",
516 info.id, info.name, info.ident, info.dep_kind);
517 let target_triple = &self.sess.opts.target_triple[..];
518 let is_cross = target_triple != config::host_triple();
519 let mut target_only = false;
520 let mut locate_ctxt = locator::Context {
524 crate_name: info.name,
526 filesearch: self.sess.host_filesearch(PathKind::Crate),
527 target: &self.sess.host,
528 triple: config::host_triple(),
530 rejected_via_hash: vec![],
531 rejected_via_triple: vec![],
532 rejected_via_kind: vec![],
533 rejected_via_version: vec![],
534 rejected_via_filename: vec![],
535 should_match_name: true,
538 let library = self.load(&mut locate_ctxt).or_else(|| {
542 // Try loading from target crates. This will abort later if we
543 // try to load a plugin registrar function,
546 locate_ctxt.target = &self.sess.target.target;
547 locate_ctxt.triple = target_triple;
548 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
550 self.load(&mut locate_ctxt)
552 let library = match library {
554 None => locate_ctxt.report_errs(),
557 let (dylib, metadata) = match library {
558 LoadResult::Previous(cnum) => {
559 let data = self.cstore.get_crate_data(cnum);
560 (data.source.dylib.clone(), PMDSource::Registered(data))
562 LoadResult::Loaded(library) => {
563 let dylib = library.dylib.clone();
564 let metadata = PMDSource::Owned(library);
571 dylib: dylib.map(|p| p.0),
572 target_only: target_only,
576 /// Load custom derive macros.
578 /// Note that this is intentionally similar to how we load plugins today,
579 /// but also intentionally separate. Plugins are likely always going to be
580 /// implemented as dynamic libraries, but we have a possible future where
581 /// custom derive (and other macro-1.1 style features) are implemented via
582 /// executables and custom IPC.
583 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
584 -> Vec<(ast::Name, Rc<SyntaxExtension>)> {
586 use proc_macro::TokenStream;
587 use proc_macro::__internal::Registry;
588 use rustc_back::dynamic_lib::DynamicLibrary;
589 use syntax_ext::deriving::custom::ProcMacroDerive;
590 use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
592 let path = match dylib {
593 Some(dylib) => dylib,
594 None => span_bug!(span, "proc-macro crate not dylib"),
596 // Make sure the path contains a / or the linker will search for it.
597 let path = env::current_dir().unwrap().join(path);
598 let lib = match DynamicLibrary::open(Some(&path)) {
600 Err(err) => self.sess.span_fatal(span, &err),
603 let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator,
604 root.macro_derive_registrar.unwrap());
605 let registrar = unsafe {
606 let sym = match lib.symbol(&sym) {
608 Err(err) => self.sess.span_fatal(span, &err),
610 mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
613 struct MyRegistrar(Vec<(ast::Name, Rc<SyntaxExtension>)>);
615 impl Registry for MyRegistrar {
616 fn register_custom_derive(&mut self,
618 expand: fn(TokenStream) -> TokenStream,
619 attributes: &[&'static str]) {
620 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
621 let derive = ProcMacroDerive::new(expand, attrs.clone());
622 let derive = SyntaxExtension::ProcMacroDerive(Box::new(derive), attrs);
623 self.0.push((Symbol::intern(trait_name), Rc::new(derive)));
626 fn register_attr_proc_macro(&mut self,
628 expand: fn(TokenStream, TokenStream) -> TokenStream) {
629 let expand = SyntaxExtension::AttrProcMacro(
630 Box::new(AttrProcMacro { inner: expand })
632 self.0.push((Symbol::intern(name), Rc::new(expand)));
635 fn register_bang_proc_macro(&mut self,
637 expand: fn(TokenStream) -> TokenStream) {
638 let expand = SyntaxExtension::ProcMacro(
639 Box::new(BangProcMacro { inner: expand })
641 self.0.push((Symbol::intern(name), Rc::new(expand)));
645 let mut my_registrar = MyRegistrar(Vec::new());
646 registrar(&mut my_registrar);
648 // Intentionally leak the dynamic library. We can't ever unload it
649 // since the library can make things that will live arbitrarily long.
654 /// Look for a plugin registrar. Returns library path, crate
655 /// SVH and DefIndex of the registrar function.
656 pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
657 -> Option<(PathBuf, Symbol, DefIndex)> {
658 let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
659 name: Symbol::intern(name),
660 ident: Symbol::intern(name),
661 id: ast::DUMMY_NODE_ID,
662 dep_kind: DepKind::UnexportedMacrosOnly,
665 if ekrate.target_only {
666 // Need to abort before syntax expansion.
667 let message = format!("plugin `{}` is not available for triple `{}` \
670 config::host_triple(),
671 self.sess.opts.target_triple);
672 span_fatal!(self.sess, span, E0456, "{}", &message);
675 let root = ekrate.metadata.get_root();
676 match (ekrate.dylib.as_ref(), root.plugin_registrar_fn) {
677 (Some(dylib), Some(reg)) => {
678 Some((dylib.to_path_buf(), root.disambiguator, reg))
681 span_err!(self.sess, span, E0457,
682 "plugin `{}` only found in rlib format, but must be available \
685 // No need to abort because the loading code will just ignore this
693 fn get_foreign_items_of_kind(&self, kind: cstore::NativeLibraryKind) -> Vec<DefIndex> {
694 let mut items = vec![];
695 let libs = self.cstore.get_used_libraries();
696 for lib in libs.borrow().iter() {
697 if relevant_lib(self.sess, lib) && lib.kind == kind {
698 items.extend(&lib.foreign_items);
704 fn register_statically_included_foreign_items(&mut self) {
705 for id in self.get_foreign_items_of_kind(cstore::NativeStatic) {
706 self.cstore.add_statically_included_foreign_item(id);
708 for id in self.get_foreign_items_of_kind(cstore::NativeStaticNobundle) {
709 self.cstore.add_statically_included_foreign_item(id);
713 fn register_dllimport_foreign_items(&mut self) {
714 let mut dllimports = self.cstore.dllimport_foreign_items.borrow_mut();
715 for id in self.get_foreign_items_of_kind(cstore::NativeUnknown) {
716 dllimports.insert(id);
720 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
721 // If we're only compiling an rlib, then there's no need to select a
722 // panic runtime, so we just skip this section entirely.
723 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
724 *ct != config::CrateTypeRlib
727 info!("panic runtime injection skipped, only generating rlib");
731 // If we need a panic runtime, we try to find an existing one here. At
732 // the same time we perform some general validation of the DAG we've got
733 // going such as ensuring everything has a compatible panic strategy.
735 // The logic for finding the panic runtime here is pretty much the same
736 // as the allocator case with the only addition that the panic strategy
737 // compilation mode also comes into play.
738 let desired_strategy = self.sess.panic_strategy();
739 let mut runtime_found = false;
740 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
741 "needs_panic_runtime");
742 self.cstore.iter_crate_data(|cnum, data| {
743 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
744 if data.is_panic_runtime() {
745 // Inject a dependency from all #![needs_panic_runtime] to this
746 // #![panic_runtime] crate.
747 self.inject_dependency_if(cnum, "a panic runtime",
748 &|data| data.needs_panic_runtime());
749 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
753 // If an explicitly linked and matching panic runtime was found, or if
754 // we just don't need one at all, then we're done here and there's
755 // nothing else to do.
756 if !needs_panic_runtime || runtime_found {
760 // By this point we know that we (a) need a panic runtime and (b) no
761 // panic runtime was explicitly linked. Here we just load an appropriate
762 // default runtime for our panic strategy and then inject the
765 // We may resolve to an already loaded crate (as the crate may not have
766 // been explicitly linked prior to this) and we may re-inject
767 // dependencies again, but both of those situations are fine.
769 // Also note that we have yet to perform validation of the crate graph
770 // in terms of everyone has a compatible panic runtime format, that's
771 // performed later as part of the `dependency_format` module.
772 let name = match desired_strategy {
773 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
774 PanicStrategy::Abort => Symbol::intern("panic_abort"),
776 info!("panic runtime not found -- loading {}", name);
778 let dep_kind = DepKind::Implicit;
780 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
782 // Sanity check the loaded crate to ensure it is indeed a panic runtime
783 // and the panic strategy is indeed what we thought it was.
784 if !data.is_panic_runtime() {
785 self.sess.err(&format!("the crate `{}` is not a panic runtime",
788 if data.panic_strategy() != desired_strategy {
789 self.sess.err(&format!("the crate `{}` does not have the panic \
791 name, desired_strategy.desc()));
794 self.sess.injected_panic_runtime.set(Some(cnum));
795 self.inject_dependency_if(cnum, "a panic runtime",
796 &|data| data.needs_panic_runtime());
799 fn inject_sanitizer_runtime(&mut self) {
800 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
801 // Sanitizers can only be used with x86_64 Linux executables linked
803 if self.sess.target.target.llvm_target != "x86_64-unknown-linux-gnu" {
804 self.sess.err(&format!("Sanitizers only work with the \
805 `x86_64-unknown-linux-gnu` target."));
809 if !self.sess.crate_types.borrow().iter().all(|ct| {
812 config::CrateTypeExecutable => true,
813 // This crate will be compiled with the required
814 // instrumentation pass
815 config::CrateTypeRlib => false,
817 self.sess.err(&format!("Only executables and rlibs can be \
818 compiled with `-Z sanitizer`"));
826 let mut uses_std = false;
827 self.cstore.iter_crate_data(|_, data| {
828 if data.name == "std" {
834 let name = match *sanitizer {
835 Sanitizer::Address => "rustc_asan",
836 Sanitizer::Leak => "rustc_lsan",
837 Sanitizer::Memory => "rustc_msan",
838 Sanitizer::Thread => "rustc_tsan",
840 info!("loading sanitizer: {}", name);
842 let symbol = Symbol::intern(name);
843 let dep_kind = DepKind::Implicit;
845 self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
846 PathKind::Crate, dep_kind);
848 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
849 if !data.is_sanitizer_runtime() {
850 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
857 fn inject_allocator_crate(&mut self) {
858 // Make sure that we actually need an allocator, if none of our
859 // dependencies need one then we definitely don't!
861 // Also, if one of our dependencies has an explicit allocator, then we
862 // also bail out as we don't need to implicitly inject one.
863 let mut needs_allocator = false;
864 let mut found_required_allocator = false;
865 self.cstore.iter_crate_data(|cnum, data| {
866 needs_allocator = needs_allocator || data.needs_allocator();
867 if data.is_allocator() {
868 info!("{} required by rlib and is an allocator", data.name());
869 self.inject_dependency_if(cnum, "an allocator",
870 &|data| data.needs_allocator());
871 found_required_allocator = found_required_allocator ||
872 data.dep_kind.get() == DepKind::Explicit;
875 if !needs_allocator || found_required_allocator { return }
877 // At this point we've determined that we need an allocator and no
878 // previous allocator has been activated. We look through our outputs of
879 // crate types to see what kind of allocator types we may need.
881 // The main special output type here is that rlibs do **not** need an
882 // allocator linked in (they're just object files), only final products
883 // (exes, dylibs, staticlibs) need allocators.
884 let mut need_lib_alloc = false;
885 let mut need_exe_alloc = false;
886 for ct in self.sess.crate_types.borrow().iter() {
888 config::CrateTypeExecutable => need_exe_alloc = true,
889 config::CrateTypeDylib |
890 config::CrateTypeProcMacro |
891 config::CrateTypeCdylib |
892 config::CrateTypeStaticlib => need_lib_alloc = true,
893 config::CrateTypeRlib => {}
896 if !need_lib_alloc && !need_exe_alloc { return }
898 // The default allocator crate comes from the custom target spec, and we
899 // choose between the standard library allocator or exe allocator. This
900 // distinction exists because the default allocator for binaries (where
901 // the world is Rust) is different than library (where the world is
902 // likely *not* Rust).
904 // If a library is being produced, but we're also flagged with `-C
905 // prefer-dynamic`, then we interpret this as a *Rust* dynamic library
906 // is being produced so we use the exe allocator instead.
908 // What this boils down to is:
910 // * Binaries use jemalloc
911 // * Staticlibs and Rust dylibs use system malloc
912 // * Rust dylibs used as dependencies to rust use jemalloc
913 let name = if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
914 Symbol::intern(&self.sess.target.target.options.lib_allocation_crate)
916 Symbol::intern(&self.sess.target.target.options.exe_allocation_crate)
918 let dep_kind = DepKind::Implicit;
920 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
922 // Sanity check the crate we loaded to ensure that it is indeed an
924 if !data.is_allocator() {
925 self.sess.err(&format!("the allocator crate `{}` is not tagged \
926 with #![allocator]", data.name()));
929 self.sess.injected_allocator.set(Some(cnum));
930 self.inject_dependency_if(cnum, "an allocator",
931 &|data| data.needs_allocator());
934 fn inject_dependency_if(&self,
937 needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
938 // don't perform this validation if the session has errors, as one of
939 // those errors may indicate a circular dependency which could cause
940 // this to stack overflow.
941 if self.sess.has_errors() {
945 // Before we inject any dependencies, make sure we don't inject a
946 // circular dependency by validating that this crate doesn't
947 // transitively depend on any crates satisfying `needs_dep`.
948 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
949 let data = self.cstore.get_crate_data(dep);
950 if needs_dep(&data) {
951 self.sess.err(&format!("the crate `{}` cannot depend \
952 on a crate that needs {}, but \
954 self.cstore.get_crate_data(krate).name(),
960 // All crates satisfying `needs_dep` do not explicitly depend on the
961 // crate provided for this compile, but in order for this compilation to
962 // be successfully linked we need to inject a dependency (to order the
963 // crates on the command line correctly).
964 self.cstore.iter_crate_data(|cnum, data| {
965 if !needs_dep(data) {
969 info!("injecting a dep from {} to {}", cnum, krate);
970 data.cnum_map.borrow_mut().push(krate);
975 impl<'a> CrateLoader<'a> {
976 pub fn preprocess(&mut self, krate: &ast::Crate) {
977 for attr in &krate.attrs {
978 if attr.path == "link_args" {
979 if let Some(linkarg) = attr.value_str() {
980 self.cstore.add_used_link_args(&linkarg.as_str());
986 fn process_foreign_mod(&mut self, i: &ast::Item, fm: &ast::ForeignMod,
987 definitions: &Definitions) {
988 if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
992 // First, add all of the custom #[link_args] attributes
993 for m in i.attrs.iter().filter(|a| a.check_name("link_args")) {
994 if let Some(linkarg) = m.value_str() {
995 self.cstore.add_used_link_args(&linkarg.as_str());
999 // Next, process all of the #[link(..)]-style arguments
1000 for m in i.attrs.iter().filter(|a| a.check_name("link")) {
1001 let items = match m.meta_item_list() {
1005 let kind = items.iter().find(|k| {
1006 k.check_name("kind")
1007 }).and_then(|a| a.value_str()).map(Symbol::as_str);
1008 let kind = match kind.as_ref().map(|s| &s[..]) {
1009 Some("static") => cstore::NativeStatic,
1010 Some("static-nobundle") => cstore::NativeStaticNobundle,
1011 Some("dylib") => cstore::NativeUnknown,
1012 Some("framework") => cstore::NativeFramework,
1014 struct_span_err!(self.sess, m.span, E0458,
1015 "unknown kind: `{}`", k)
1016 .span_label(m.span, &format!("unknown kind")).emit();
1017 cstore::NativeUnknown
1019 None => cstore::NativeUnknown
1021 let n = items.iter().find(|n| {
1022 n.check_name("name")
1023 }).and_then(|a| a.value_str());
1027 struct_span_err!(self.sess, m.span, E0459,
1028 "#[link(...)] specified without `name = \"foo\"`")
1029 .span_label(m.span, &format!("missing `name` argument")).emit();
1030 Symbol::intern("foo")
1033 let cfg = items.iter().find(|k| {
1035 }).and_then(|a| a.meta_item_list());
1036 let cfg = cfg.map(|list| {
1037 list[0].meta_item().unwrap().clone()
1039 let foreign_items = fm.items.iter()
1040 .map(|it| definitions.opt_def_index(it.id).unwrap())
1042 let lib = NativeLibrary {
1046 foreign_items: foreign_items,
1048 register_native_lib(self.sess, self.cstore, Some(m.span), lib);
1053 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
1054 fn postprocess(&mut self, krate: &ast::Crate) {
1055 // inject the sanitizer runtime before the allocator runtime because all
1056 // sanitizers force the use of the `alloc_system` allocator
1057 self.inject_sanitizer_runtime();
1058 self.inject_allocator_crate();
1059 self.inject_panic_runtime(krate);
1061 if log_enabled!(log::LogLevel::Info) {
1062 dump_crates(&self.cstore);
1065 // Process libs passed on the command line
1066 // First, check for errors
1067 let mut renames = FxHashSet();
1068 for &(ref name, ref new_name, _) in &self.sess.opts.libs {
1069 if let &Some(ref new_name) = new_name {
1070 if new_name.is_empty() {
1072 &format!("an empty renaming target was specified for library `{}`",name));
1073 } else if !self.cstore.get_used_libraries().borrow().iter()
1074 .any(|lib| lib.name == name as &str) {
1075 self.sess.err(&format!("renaming of the library `{}` was specified, \
1076 however this crate contains no #[link(...)] \
1077 attributes referencing this library.", name));
1078 } else if renames.contains(name) {
1079 self.sess.err(&format!("multiple renamings were specified for library `{}` .",
1082 renames.insert(name);
1086 // Update kind and, optionally, the name of all native libaries
1087 // (there may be more than one) with the specified name.
1088 for &(ref name, ref new_name, kind) in &self.sess.opts.libs {
1089 let mut found = false;
1090 for lib in self.cstore.get_used_libraries().borrow_mut().iter_mut() {
1091 if lib.name == name as &str {
1092 let mut changed = false;
1093 if let Some(k) = kind {
1097 if let &Some(ref new_name) = new_name {
1098 lib.name = Symbol::intern(new_name);
1102 self.sess.warn(&format!("redundant linker flag specified for library `{}`",
1111 let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
1112 let lib = NativeLibrary {
1113 name: Symbol::intern(new_name.unwrap_or(name)),
1114 kind: if let Some(k) = kind { k } else { cstore::NativeUnknown },
1116 foreign_items: Vec::new(),
1118 register_native_lib(self.sess, self.cstore, None, lib);
1121 self.register_statically_included_foreign_items();
1122 self.register_dllimport_foreign_items();
1125 fn process_item(&mut self, item: &ast::Item, definitions: &Definitions) {
1127 ast::ItemKind::ForeignMod(ref fm) => {
1128 self.process_foreign_mod(item, fm, definitions)
1130 ast::ItemKind::ExternCrate(_) => {
1131 let info = self.extract_crate_info(item).unwrap();
1132 let (cnum, ..) = self.resolve_crate(
1133 &None, info.ident, info.name, None, item.span, PathKind::Crate, info.dep_kind,
1136 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1137 let len = definitions.def_path(def_id.index).data.len();
1140 ExternCrate { def_id: def_id, span: item.span, direct: true, path_len: len };
1141 self.update_extern_crate(cnum, extern_crate, &mut FxHashSet());
1142 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);