1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Validates all used crates and extern libraries and loads their metadata
13 use cstore::{self, CStore, CrateSource, MetadataBlob};
14 use locator::{self, CratePaths};
15 use native_libs::relevant_lib;
16 use schema::CrateRoot;
18 use rustc::hir::def_id::{CrateNum, DefIndex, CRATE_DEF_INDEX};
19 use rustc::hir::svh::Svh;
20 use rustc::middle::allocator::AllocatorKind;
21 use rustc::middle::cstore::DepKind;
22 use rustc::session::Session;
23 use rustc::session::config::{Sanitizer, self};
24 use rustc_back::PanicStrategy;
25 use rustc::session::search_paths::PathKind;
27 use rustc::middle::cstore::{validate_crate_name, ExternCrate};
28 use rustc::util::common::record_time;
29 use rustc::util::nodemap::FxHashSet;
30 use rustc::hir::map::Definitions;
32 use std::cell::{RefCell, Cell};
34 use std::path::PathBuf;
40 use syntax::ext::base::SyntaxExtension;
41 use syntax::symbol::Symbol;
43 use syntax_pos::{Span, DUMMY_SP};
47 pub dylib: Option<(PathBuf, PathKind)>,
48 pub rlib: Option<(PathBuf, PathKind)>,
49 pub rmeta: Option<(PathBuf, PathKind)>,
50 pub metadata: MetadataBlob,
53 pub struct CrateLoader<'a> {
54 pub sess: &'a Session,
56 next_crate_num: CrateNum,
57 local_crate_name: Symbol,
60 fn dump_crates(cstore: &CStore) {
61 info!("resolved crates:");
62 cstore.iter_crate_data(|_, data| {
63 info!(" name: {}", data.name());
64 info!(" cnum: {}", data.cnum);
65 info!(" hash: {}", data.hash());
66 info!(" reqd: {:?}", data.dep_kind.get());
67 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
68 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
69 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
70 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
75 struct ExternCrateInfo {
82 // Extra info about a crate loaded for plugins or exported macros.
83 struct ExtensionCrate {
85 dylib: Option<PathBuf>,
90 Registered(Rc<cstore::CrateMetadata>),
94 impl Deref for PMDSource {
95 type Target = MetadataBlob;
97 fn deref(&self) -> &MetadataBlob {
99 PMDSource::Registered(ref cmd) => &cmd.blob,
100 PMDSource::Owned(ref lib) => &lib.metadata
110 impl<'a> CrateLoader<'a> {
111 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
115 next_crate_num: cstore.next_crate_num(),
116 local_crate_name: Symbol::intern(local_crate_name),
120 fn extract_crate_info(&self, i: &ast::Item) -> Option<ExternCrateInfo> {
122 ast::ItemKind::ExternCrate(ref path_opt) => {
123 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
125 let name = match *path_opt {
127 validate_crate_name(Some(self.sess), &name.as_str(),
131 None => i.ident.name,
133 Some(ExternCrateInfo {
137 dep_kind: if attr::contains_name(&i.attrs, "no_link") {
138 DepKind::UnexportedMacrosOnly
148 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
149 -> Option<CrateNum> {
151 self.cstore.iter_crate_data(|cnum, data| {
152 if data.name != name { return }
155 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
160 // When the hash is None we're dealing with a top-level dependency
161 // in which case we may have a specification on the command line for
162 // this library. Even though an upstream library may have loaded
163 // something of the same name, we have to make sure it was loaded
164 // from the exact same location as well.
166 // We're also sure to compare *paths*, not actual byte slices. The
167 // `source` stores paths which are normalized which may be different
168 // from the strings on the command line.
169 let source = &self.cstore.get_crate_data(cnum).source;
170 if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
171 let found = locs.iter().any(|l| {
172 let l = fs::canonicalize(l).ok();
173 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
174 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
182 // Alright, so we've gotten this far which means that `data` has the
183 // right name, we don't have a hash, and we don't have a --extern
184 // pointing for ourselves. We're still not quite yet done because we
185 // have to make sure that this crate was found in the crate lookup
186 // path (this is a top-level dependency) as we don't want to
187 // implicitly load anything inside the dependency lookup path.
188 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
189 .or(source.rmeta.as_ref())
190 .expect("No sources for crate").1;
191 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
198 fn verify_no_symbol_conflicts(&self,
201 // Check for (potential) conflicts with the local crate
202 if self.local_crate_name == root.name &&
203 self.sess.local_crate_disambiguator() == root.disambiguator {
204 span_fatal!(self.sess, span, E0519,
205 "the current crate is indistinguishable from one of its \
206 dependencies: it has the same crate-name `{}` and was \
207 compiled with the same `-C metadata` arguments. This \
208 will result in symbol conflicts between the two.",
212 // Check for conflicts with any crate loaded so far
213 self.cstore.iter_crate_data(|_, other| {
214 if other.name() == root.name && // same crate-name
215 other.disambiguator() == root.disambiguator && // same crate-disambiguator
216 other.hash() != root.hash { // but different SVH
217 span_fatal!(self.sess, span, E0523,
218 "found two different crates with name `{}` that are \
219 not distinguished by differing `-C metadata`. This \
220 will result in symbol conflicts between the two.",
226 fn register_crate(&mut self,
227 root: &Option<CratePaths>,
233 -> (CrateNum, Rc<cstore::CrateMetadata>) {
234 info!("register crate `extern crate {} as {}`", name, ident);
235 let crate_root = lib.metadata.get_root();
236 self.verify_no_symbol_conflicts(span, &crate_root);
238 // Claim this crate number and cache it
239 let cnum = self.next_crate_num;
240 self.next_crate_num = CrateNum::from_u32(cnum.as_u32() + 1);
242 // Stash paths for top-most crate locally if necessary.
243 let crate_paths = if root.is_none() {
245 ident: ident.to_string(),
246 dylib: lib.dylib.clone().map(|p| p.0),
247 rlib: lib.rlib.clone().map(|p| p.0),
248 rmeta: lib.rmeta.clone().map(|p| p.0),
253 // Maintain a reference to the top most crate.
254 let root = if root.is_some() { root } else { &crate_paths };
256 let Library { dylib, rlib, rmeta, metadata } = lib;
258 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
260 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
261 crate_root.def_path_table.decode(&metadata)
264 let exported_symbols = crate_root.exported_symbols.decode(&metadata).collect();
266 let trait_impls = crate_root
269 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
272 let mut cmeta = cstore::CrateMetadata {
274 extern_crate: Cell::new(None),
275 def_path_table: Rc::new(def_path_table),
278 proc_macros: crate_root.macro_derive_registrar.map(|_| {
279 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
283 cnum_map: RefCell::new(cnum_map),
285 codemap_import_info: RefCell::new(vec![]),
286 attribute_cache: RefCell::new([Vec::new(), Vec::new()]),
287 dep_kind: Cell::new(dep_kind),
288 source: cstore::CrateSource {
293 // Initialize this with an empty set. The field is populated below
294 // after we were able to deserialize its contents.
295 dllimport_foreign_items: FxHashSet(),
298 let dllimports: FxHashSet<_> = cmeta
302 .filter(|lib| relevant_lib(self.sess, lib) &&
303 lib.kind == cstore::NativeLibraryKind::NativeUnknown)
305 assert!(lib.foreign_items.iter().all(|def_id| def_id.krate == cnum));
306 lib.foreign_items.into_iter().map(|def_id| def_id.index)
310 cmeta.dllimport_foreign_items = dllimports;
312 let cmeta = Rc::new(cmeta);
313 self.cstore.set_crate_data(cnum, cmeta.clone());
317 fn resolve_crate(&mut self,
318 root: &Option<CratePaths>,
324 mut dep_kind: DepKind)
325 -> (CrateNum, Rc<cstore::CrateMetadata>) {
326 info!("resolving crate `extern crate {} as {}`", name, ident);
327 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
328 LoadResult::Previous(cnum)
330 info!("falling back to a load");
331 let mut locate_ctxt = locator::Context {
336 hash: hash.map(|a| &*a),
337 filesearch: self.sess.target_filesearch(path_kind),
338 target: &self.sess.target.target,
339 triple: &self.sess.opts.target_triple,
341 rejected_via_hash: vec![],
342 rejected_via_triple: vec![],
343 rejected_via_kind: vec![],
344 rejected_via_version: vec![],
345 rejected_via_filename: vec![],
346 should_match_name: true,
347 is_proc_macro: Some(false),
348 metadata_loader: &*self.cstore.metadata_loader,
351 self.load(&mut locate_ctxt).or_else(|| {
352 dep_kind = DepKind::UnexportedMacrosOnly;
354 let mut proc_macro_locator = locator::Context {
355 target: &self.sess.host,
356 triple: config::host_triple(),
357 filesearch: self.sess.host_filesearch(path_kind),
358 rejected_via_hash: vec![],
359 rejected_via_triple: vec![],
360 rejected_via_kind: vec![],
361 rejected_via_version: vec![],
362 rejected_via_filename: vec![],
363 is_proc_macro: Some(true),
367 self.load(&mut proc_macro_locator)
368 }).unwrap_or_else(|| locate_ctxt.report_errs())
372 LoadResult::Previous(cnum) => {
373 let data = self.cstore.get_crate_data(cnum);
374 if data.root.macro_derive_registrar.is_some() {
375 dep_kind = DepKind::UnexportedMacrosOnly;
377 data.dep_kind.set(cmp::max(data.dep_kind.get(), dep_kind));
380 LoadResult::Loaded(library) => {
381 self.register_crate(root, ident, name, span, library, dep_kind)
386 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
387 let library = match locate_ctxt.maybe_load_library_crate() {
392 // In the case that we're loading a crate, but not matching
393 // against a hash, we could load a crate which has the same hash
394 // as an already loaded crate. If this is the case prevent
395 // duplicates by just using the first crate.
397 // Note that we only do this for target triple crates, though, as we
398 // don't want to match a host crate against an equivalent target one
400 let root = library.metadata.get_root();
401 if locate_ctxt.triple == self.sess.opts.target_triple {
402 let mut result = LoadResult::Loaded(library);
403 self.cstore.iter_crate_data(|cnum, data| {
404 if data.name() == root.name && root.hash == data.hash() {
405 assert!(locate_ctxt.hash.is_none());
406 info!("load success, going to previous cnum: {}", cnum);
407 result = LoadResult::Previous(cnum);
412 Some(LoadResult::Loaded(library))
416 fn update_extern_crate(&mut self,
418 mut extern_crate: ExternCrate,
419 visited: &mut FxHashSet<(CrateNum, bool)>)
421 if !visited.insert((cnum, extern_crate.direct)) { return }
423 let cmeta = self.cstore.get_crate_data(cnum);
424 let old_extern_crate = cmeta.extern_crate.get();
427 // - something over nothing (tuple.0);
428 // - direct extern crate to indirect (tuple.1);
429 // - shorter paths to longer (tuple.2).
430 let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
431 let old_rank = match old_extern_crate {
432 None => (false, false, !0),
433 Some(ref c) => (true, c.direct, !c.path_len),
436 if old_rank >= new_rank {
437 return; // no change needed
440 cmeta.extern_crate.set(Some(extern_crate));
441 // Propagate the extern crate info to dependencies.
442 extern_crate.direct = false;
443 for &dep_cnum in cmeta.cnum_map.borrow().iter() {
444 self.update_extern_crate(dep_cnum, extern_crate, visited);
448 // Go through the crate metadata and load any crates that it references
449 fn resolve_crate_deps(&mut self,
450 root: &Option<CratePaths>,
451 crate_root: &CrateRoot,
452 metadata: &MetadataBlob,
456 -> cstore::CrateNumMap {
457 debug!("resolving deps of external crate");
458 if crate_root.macro_derive_registrar.is_some() {
459 return cstore::CrateNumMap::new();
462 // The map from crate numbers in the crate we're resolving to local crate numbers.
463 // We map 0 and all other holes in the map to our parent crate. The "additional"
464 // self-dependencies should be harmless.
465 ::std::iter::once(krate).chain(crate_root.crate_deps
468 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
469 if dep.kind == DepKind::UnexportedMacrosOnly {
472 let dep_kind = match dep_kind {
473 DepKind::MacrosOnly => DepKind::MacrosOnly,
476 let (local_cnum, ..) = self.resolve_crate(
477 root, dep.name, dep.name, Some(&dep.hash), span, PathKind::Dependency, dep_kind,
483 fn read_extension_crate(&mut self, span: Span, info: &ExternCrateInfo) -> ExtensionCrate {
484 info!("read extension crate {} `extern crate {} as {}` dep_kind={:?}",
485 info.id, info.name, info.ident, info.dep_kind);
486 let target_triple = &self.sess.opts.target_triple[..];
487 let is_cross = target_triple != config::host_triple();
488 let mut target_only = false;
489 let mut locate_ctxt = locator::Context {
493 crate_name: info.name,
495 filesearch: self.sess.host_filesearch(PathKind::Crate),
496 target: &self.sess.host,
497 triple: config::host_triple(),
499 rejected_via_hash: vec![],
500 rejected_via_triple: vec![],
501 rejected_via_kind: vec![],
502 rejected_via_version: vec![],
503 rejected_via_filename: vec![],
504 should_match_name: true,
506 metadata_loader: &*self.cstore.metadata_loader,
508 let library = self.load(&mut locate_ctxt).or_else(|| {
512 // Try loading from target crates. This will abort later if we
513 // try to load a plugin registrar function,
516 locate_ctxt.target = &self.sess.target.target;
517 locate_ctxt.triple = target_triple;
518 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
520 self.load(&mut locate_ctxt)
522 let library = match library {
524 None => locate_ctxt.report_errs(),
527 let (dylib, metadata) = match library {
528 LoadResult::Previous(cnum) => {
529 let data = self.cstore.get_crate_data(cnum);
530 (data.source.dylib.clone(), PMDSource::Registered(data))
532 LoadResult::Loaded(library) => {
533 let dylib = library.dylib.clone();
534 let metadata = PMDSource::Owned(library);
541 dylib: dylib.map(|p| p.0),
546 /// Load custom derive macros.
548 /// Note that this is intentionally similar to how we load plugins today,
549 /// but also intentionally separate. Plugins are likely always going to be
550 /// implemented as dynamic libraries, but we have a possible future where
551 /// custom derive (and other macro-1.1 style features) are implemented via
552 /// executables and custom IPC.
553 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
554 -> Vec<(ast::Name, Rc<SyntaxExtension>)> {
556 use proc_macro::TokenStream;
557 use proc_macro::__internal::Registry;
558 use rustc_back::dynamic_lib::DynamicLibrary;
559 use syntax_ext::deriving::custom::ProcMacroDerive;
560 use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
562 let path = match dylib {
563 Some(dylib) => dylib,
564 None => span_bug!(span, "proc-macro crate not dylib"),
566 // Make sure the path contains a / or the linker will search for it.
567 let path = env::current_dir().unwrap().join(path);
568 let lib = match DynamicLibrary::open(Some(&path)) {
570 Err(err) => self.sess.span_fatal(span, &err),
573 let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator,
574 root.macro_derive_registrar.unwrap());
575 let registrar = unsafe {
576 let sym = match lib.symbol(&sym) {
578 Err(err) => self.sess.span_fatal(span, &err),
580 mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
583 struct MyRegistrar(Vec<(ast::Name, Rc<SyntaxExtension>)>);
585 impl Registry for MyRegistrar {
586 fn register_custom_derive(&mut self,
588 expand: fn(TokenStream) -> TokenStream,
589 attributes: &[&'static str]) {
590 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
591 let derive = ProcMacroDerive::new(expand, attrs.clone());
592 let derive = SyntaxExtension::ProcMacroDerive(Box::new(derive), attrs);
593 self.0.push((Symbol::intern(trait_name), Rc::new(derive)));
596 fn register_attr_proc_macro(&mut self,
598 expand: fn(TokenStream, TokenStream) -> TokenStream) {
599 let expand = SyntaxExtension::AttrProcMacro(
600 Box::new(AttrProcMacro { inner: expand })
602 self.0.push((Symbol::intern(name), Rc::new(expand)));
605 fn register_bang_proc_macro(&mut self,
607 expand: fn(TokenStream) -> TokenStream) {
608 let expand = SyntaxExtension::ProcMacro(
609 Box::new(BangProcMacro { inner: expand })
611 self.0.push((Symbol::intern(name), Rc::new(expand)));
615 let mut my_registrar = MyRegistrar(Vec::new());
616 registrar(&mut my_registrar);
618 // Intentionally leak the dynamic library. We can't ever unload it
619 // since the library can make things that will live arbitrarily long.
624 /// Look for a plugin registrar. Returns library path, crate
625 /// SVH and DefIndex of the registrar function.
626 pub fn find_plugin_registrar(&mut self,
629 -> Option<(PathBuf, Symbol, DefIndex)> {
630 let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
631 name: Symbol::intern(name),
632 ident: Symbol::intern(name),
633 id: ast::DUMMY_NODE_ID,
634 dep_kind: DepKind::UnexportedMacrosOnly,
637 if ekrate.target_only {
638 // Need to abort before syntax expansion.
639 let message = format!("plugin `{}` is not available for triple `{}` \
642 config::host_triple(),
643 self.sess.opts.target_triple);
644 span_fatal!(self.sess, span, E0456, "{}", &message);
647 let root = ekrate.metadata.get_root();
648 match (ekrate.dylib.as_ref(), root.plugin_registrar_fn) {
649 (Some(dylib), Some(reg)) => {
650 Some((dylib.to_path_buf(), root.disambiguator, reg))
653 span_err!(self.sess, span, E0457,
654 "plugin `{}` only found in rlib format, but must be available \
657 // No need to abort because the loading code will just ignore this
665 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
666 // If we're only compiling an rlib, then there's no need to select a
667 // panic runtime, so we just skip this section entirely.
668 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
669 *ct != config::CrateTypeRlib
672 info!("panic runtime injection skipped, only generating rlib");
676 // If we need a panic runtime, we try to find an existing one here. At
677 // the same time we perform some general validation of the DAG we've got
678 // going such as ensuring everything has a compatible panic strategy.
680 // The logic for finding the panic runtime here is pretty much the same
681 // as the allocator case with the only addition that the panic strategy
682 // compilation mode also comes into play.
683 let desired_strategy = self.sess.panic_strategy();
684 let mut runtime_found = false;
685 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
686 "needs_panic_runtime");
688 self.cstore.iter_crate_data(|cnum, data| {
689 needs_panic_runtime = needs_panic_runtime ||
690 data.needs_panic_runtime();
691 if data.is_panic_runtime() {
692 // Inject a dependency from all #![needs_panic_runtime] to this
693 // #![panic_runtime] crate.
694 self.inject_dependency_if(cnum, "a panic runtime",
695 &|data| data.needs_panic_runtime());
696 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
700 // If an explicitly linked and matching panic runtime was found, or if
701 // we just don't need one at all, then we're done here and there's
702 // nothing else to do.
703 if !needs_panic_runtime || runtime_found {
707 // By this point we know that we (a) need a panic runtime and (b) no
708 // panic runtime was explicitly linked. Here we just load an appropriate
709 // default runtime for our panic strategy and then inject the
712 // We may resolve to an already loaded crate (as the crate may not have
713 // been explicitly linked prior to this) and we may re-inject
714 // dependencies again, but both of those situations are fine.
716 // Also note that we have yet to perform validation of the crate graph
717 // in terms of everyone has a compatible panic runtime format, that's
718 // performed later as part of the `dependency_format` module.
719 let name = match desired_strategy {
720 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
721 PanicStrategy::Abort => Symbol::intern("panic_abort"),
723 info!("panic runtime not found -- loading {}", name);
725 let dep_kind = DepKind::Implicit;
727 self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
729 // Sanity check the loaded crate to ensure it is indeed a panic runtime
730 // and the panic strategy is indeed what we thought it was.
731 if !data.is_panic_runtime() {
732 self.sess.err(&format!("the crate `{}` is not a panic runtime",
735 if data.panic_strategy() != desired_strategy {
736 self.sess.err(&format!("the crate `{}` does not have the panic \
738 name, desired_strategy.desc()));
741 self.sess.injected_panic_runtime.set(Some(cnum));
742 self.inject_dependency_if(cnum, "a panic runtime",
743 &|data| data.needs_panic_runtime());
746 fn inject_sanitizer_runtime(&mut self) {
747 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
748 // Sanitizers can only be used on some tested platforms with
749 // executables linked to `std`
750 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
751 "x86_64-apple-darwin"];
752 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
753 "x86_64-apple-darwin"];
754 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
755 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
757 let supported_targets = match *sanitizer {
758 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
759 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
760 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
761 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
763 if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
764 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
766 supported_targets.join("` or `")
771 // firstyear 2017 - during testing I was unable to access an OSX machine
772 // to make this work on different crate types. As a result, today I have
773 // only been able to test and support linux as a target.
774 if self.sess.target.target.llvm_target == "x86_64-unknown-linux-gnu" {
775 if !self.sess.crate_types.borrow().iter().all(|ct| {
778 config::CrateTypeStaticlib |
779 config::CrateTypeExecutable => true,
780 // This crate will be compiled with the required
781 // instrumentation pass
782 config::CrateTypeRlib |
783 config::CrateTypeDylib |
784 config::CrateTypeCdylib =>
787 self.sess.err(&format!("Only executables, staticlibs, \
788 cdylibs, dylibs and rlibs can be compiled with \
797 if !self.sess.crate_types.borrow().iter().all(|ct| {
800 config::CrateTypeExecutable => true,
801 // This crate will be compiled with the required
802 // instrumentation pass
803 config::CrateTypeRlib => false,
805 self.sess.err(&format!("Only executables and rlibs can be \
806 compiled with `-Z sanitizer`"));
815 let mut uses_std = false;
816 self.cstore.iter_crate_data(|_, data| {
817 if data.name == "std" {
823 let name = match *sanitizer {
824 Sanitizer::Address => "rustc_asan",
825 Sanitizer::Leak => "rustc_lsan",
826 Sanitizer::Memory => "rustc_msan",
827 Sanitizer::Thread => "rustc_tsan",
829 info!("loading sanitizer: {}", name);
831 let symbol = Symbol::intern(name);
832 let dep_kind = DepKind::Explicit;
834 self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
835 PathKind::Crate, dep_kind);
837 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
838 if !data.is_sanitizer_runtime() {
839 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
843 self.sess.err(&format!("Must link std to be compiled with `-Z sanitizer`"));
848 fn inject_profiler_runtime(&mut self) {
849 if self.sess.opts.debugging_opts.profile {
850 info!("loading profiler");
852 let symbol = Symbol::intern("profiler_builtins");
853 let dep_kind = DepKind::Implicit;
855 self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
856 PathKind::Crate, dep_kind);
858 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
859 if !data.is_profiler_runtime() {
860 self.sess.err(&format!("the crate `profiler_builtins` is not \
861 a profiler runtime"));
866 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
867 let has_global_allocator = has_global_allocator(krate);
868 if has_global_allocator {
869 self.sess.has_global_allocator.set(true);
872 // Check to see if we actually need an allocator. This desire comes
873 // about through the `#![needs_allocator]` attribute and is typically
874 // written down in liballoc.
875 let mut needs_allocator = attr::contains_name(&krate.attrs,
877 self.cstore.iter_crate_data(|_, data| {
878 needs_allocator = needs_allocator || data.needs_allocator();
880 if !needs_allocator {
884 // At this point we've determined that we need an allocator. Let's see
885 // if our compilation session actually needs an allocator based on what
887 let mut need_lib_alloc = false;
888 let mut need_exe_alloc = false;
889 for ct in self.sess.crate_types.borrow().iter() {
891 config::CrateTypeExecutable => need_exe_alloc = true,
892 config::CrateTypeDylib |
893 config::CrateTypeProcMacro |
894 config::CrateTypeCdylib |
895 config::CrateTypeStaticlib => need_lib_alloc = true,
896 config::CrateTypeRlib => {}
899 if !need_lib_alloc && !need_exe_alloc {
903 // Ok, we need an allocator. Not only that but we're actually going to
904 // create an artifact that needs one linked in. Let's go find the one
905 // that we're going to link in.
907 // First up we check for global allocators. Look at the crate graph here
908 // and see what's a global allocator, including if we ourselves are a
910 let mut global_allocator = if has_global_allocator {
915 self.cstore.iter_crate_data(|_, data| {
916 if !data.has_global_allocator() {
919 match global_allocator {
920 Some(Some(other_crate)) => {
921 self.sess.err(&format!("the #[global_allocator] in {} \
922 conflicts with this global \
928 self.sess.err(&format!("the #[global_allocator] in this \
929 crate conflicts with global \
930 allocator in: {}", data.name()));
932 None => global_allocator = Some(Some(data.name())),
935 if global_allocator.is_some() {
936 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
940 // Ok we haven't found a global allocator but we still need an
941 // allocator. At this point we'll either fall back to the "library
942 // allocator" or the "exe allocator" depending on a few variables. Let's
943 // figure out which one.
945 // Note that here we favor linking to the "library allocator" as much as
946 // possible. If we're not creating rustc's version of libstd
947 // (need_lib_alloc and prefer_dynamic) then we select `None`, and if the
948 // exe allocation crate doesn't exist for this target then we also
950 let exe_allocation_crate_data =
951 if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
958 .exe_allocation_crate
961 // We've determined that we're injecting an "exe allocator" which means
962 // that we're going to load up a whole new crate. An example of this is
963 // that we're producing a normal binary on Linux which means we need to
964 // load the `alloc_jemalloc` crate to link as an allocator.
965 let name = Symbol::intern(name);
966 let (cnum, data) = self.resolve_crate(&None,
973 self.sess.injected_allocator.set(Some(cnum));
978 let allocation_crate_data = exe_allocation_crate_data.or_else(|| {
979 if attr::contains_name(&krate.attrs, "default_lib_allocator") {
980 // Prefer self as the allocator if there's a collision
983 // We're not actually going to inject an allocator, we're going to
984 // require that something in our crate graph is the default lib
985 // allocator. This is typically libstd, so this'll rarely be an
987 let mut allocator = None;
988 self.cstore.iter_crate_data(|_, data| {
989 if allocator.is_none() && data.has_default_lib_allocator() {
990 allocator = Some(data.clone());
996 match allocation_crate_data {
998 // We have an allocator. We detect separately what kind it is, to allow for some
999 // flexibility in misconfiguration.
1000 let attrs = data.get_item_attrs(CRATE_DEF_INDEX);
1001 let kind_interned = attr::first_attr_value_str_by_name(&attrs, "rustc_alloc_kind")
1002 .map(Symbol::as_str);
1003 let kind_str = kind_interned
1005 .map(|s| s as &str);
1006 let alloc_kind = match kind_str {
1008 Some("lib") => AllocatorKind::DefaultLib,
1009 Some("exe") => AllocatorKind::DefaultExe,
1011 self.sess.err(&format!("Allocator kind {} not known", other));
1015 self.sess.allocator_kind.set(Some(alloc_kind));
1018 if !attr::contains_name(&krate.attrs, "default_lib_allocator") {
1019 self.sess.err("no #[default_lib_allocator] found but one is \
1020 required; is libstd not linked?");
1023 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
1027 fn has_global_allocator(krate: &ast::Crate) -> bool {
1028 struct Finder(bool);
1029 let mut f = Finder(false);
1030 visit::walk_crate(&mut f, krate);
1033 impl<'ast> visit::Visitor<'ast> for Finder {
1034 fn visit_item(&mut self, i: &'ast ast::Item) {
1035 if attr::contains_name(&i.attrs, "global_allocator") {
1038 visit::walk_item(self, i)
1045 fn inject_dependency_if(&self,
1048 needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
1049 // don't perform this validation if the session has errors, as one of
1050 // those errors may indicate a circular dependency which could cause
1051 // this to stack overflow.
1052 if self.sess.has_errors() {
1056 // Before we inject any dependencies, make sure we don't inject a
1057 // circular dependency by validating that this crate doesn't
1058 // transitively depend on any crates satisfying `needs_dep`.
1059 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
1060 let data = self.cstore.get_crate_data(dep);
1061 if needs_dep(&data) {
1062 self.sess.err(&format!("the crate `{}` cannot depend \
1063 on a crate that needs {}, but \
1064 it depends on `{}`",
1065 self.cstore.get_crate_data(krate).name(),
1071 // All crates satisfying `needs_dep` do not explicitly depend on the
1072 // crate provided for this compile, but in order for this compilation to
1073 // be successfully linked we need to inject a dependency (to order the
1074 // crates on the command line correctly).
1075 self.cstore.iter_crate_data(|cnum, data| {
1076 if !needs_dep(data) {
1080 info!("injecting a dep from {} to {}", cnum, krate);
1081 data.cnum_map.borrow_mut().push(krate);
1086 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
1087 fn postprocess(&mut self, krate: &ast::Crate) {
1088 // inject the sanitizer runtime before the allocator runtime because all
1089 // sanitizers force the use of the `alloc_system` allocator
1090 self.inject_sanitizer_runtime();
1091 self.inject_profiler_runtime();
1092 self.inject_allocator_crate(krate);
1093 self.inject_panic_runtime(krate);
1095 if log_enabled!(log::LogLevel::Info) {
1096 dump_crates(&self.cstore);
1100 fn process_item(&mut self, item: &ast::Item, definitions: &Definitions) {
1102 ast::ItemKind::ExternCrate(_) => {
1103 let info = self.extract_crate_info(item).unwrap();
1104 let (cnum, ..) = self.resolve_crate(
1105 &None, info.ident, info.name, None, item.span, PathKind::Crate, info.dep_kind,
1108 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1109 let len = definitions.def_path(def_id.index).data.len();
1112 ExternCrate { def_id: def_id, span: item.span, direct: true, path_len: len };
1113 self.update_extern_crate(cnum, extern_crate, &mut FxHashSet());
1114 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);