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 decoder::proc_macro_def_path_table;
16 use schema::CrateRoot;
17 use rustc_data_structures::sync::{Lrc, RwLock, Lock};
19 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX};
20 use rustc_data_structures::svh::Svh;
21 use rustc::middle::allocator::AllocatorKind;
22 use rustc::middle::cstore::DepKind;
23 use rustc::mir::interpret::AllocDecodingState;
24 use rustc::session::{Session, CrateDisambiguator};
25 use rustc::session::config::{Sanitizer, self};
26 use rustc_target::spec::{PanicStrategy, TargetTriple};
27 use rustc::session::search_paths::PathKind;
28 use rustc::middle::cstore::{ExternCrate, ExternCrateSource};
29 use rustc::util::common::record_time;
30 use rustc::util::nodemap::FxHashSet;
31 use rustc::hir::map::Definitions;
33 use rustc_metadata_utils::validate_crate_name;
36 use std::path::PathBuf;
41 use syntax::edition::Edition;
42 use syntax::ext::base::SyntaxExtension;
43 use syntax::symbol::Symbol;
45 use syntax_pos::{Span, DUMMY_SP};
49 pub dylib: Option<(PathBuf, PathKind)>,
50 pub rlib: Option<(PathBuf, PathKind)>,
51 pub rmeta: Option<(PathBuf, PathKind)>,
52 pub metadata: MetadataBlob,
55 pub struct CrateLoader<'a> {
56 pub sess: &'a Session,
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.root.name);
65 info!(" cnum: {}", data.cnum);
66 info!(" hash: {}", data.root.hash);
67 info!(" reqd: {:?}", *data.dep_kind.lock());
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()));
75 // Extra info about a crate loaded for plugins or exported macros.
76 struct ExtensionCrate {
78 dylib: Option<PathBuf>,
83 Registered(Lrc<cstore::CrateMetadata>),
87 impl Deref for PMDSource {
88 type Target = MetadataBlob;
90 fn deref(&self) -> &MetadataBlob {
92 PMDSource::Registered(ref cmd) => &cmd.blob,
93 PMDSource::Owned(ref lib) => &lib.metadata
104 LocatorError(locator::Context<'a>),
107 impl<'a> LoadError<'a> {
108 fn report(self) -> ! {
110 LoadError::LocatorError(mut locate_ctxt) => locate_ctxt.report_errs(),
115 impl<'a> CrateLoader<'a> {
116 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
120 local_crate_name: Symbol::intern(local_crate_name),
124 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
125 -> Option<CrateNum> {
127 self.cstore.iter_crate_data(|cnum, data| {
128 if data.name != name { return }
131 Some(hash) if *hash == data.root.hash => { ret = Some(cnum); return }
136 // When the hash is None we're dealing with a top-level dependency
137 // in which case we may have a specification on the command line for
138 // this library. Even though an upstream library may have loaded
139 // something of the same name, we have to make sure it was loaded
140 // from the exact same location as well.
142 // We're also sure to compare *paths*, not actual byte slices. The
143 // `source` stores paths which are normalized which may be different
144 // from the strings on the command line.
145 let source = &self.cstore.get_crate_data(cnum).source;
146 if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
147 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
148 let found = locs.iter().filter_map(|l| l.as_ref()).any(|l| {
149 let l = fs::canonicalize(l).ok();
150 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
151 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
159 // Alright, so we've gotten this far which means that `data` has the
160 // right name, we don't have a hash, and we don't have a --extern
161 // pointing for ourselves. We're still not quite yet done because we
162 // have to make sure that this crate was found in the crate lookup
163 // path (this is a top-level dependency) as we don't want to
164 // implicitly load anything inside the dependency lookup path.
165 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
166 .or(source.rmeta.as_ref())
167 .expect("No sources for crate").1;
168 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
175 fn verify_no_symbol_conflicts(&self,
178 // Check for (potential) conflicts with the local crate
179 if self.local_crate_name == root.name &&
180 self.sess.local_crate_disambiguator() == root.disambiguator {
181 span_fatal!(self.sess, span, E0519,
182 "the current crate is indistinguishable from one of its \
183 dependencies: it has the same crate-name `{}` and was \
184 compiled with the same `-C metadata` arguments. This \
185 will result in symbol conflicts between the two.",
189 // Check for conflicts with any crate loaded so far
190 self.cstore.iter_crate_data(|_, other| {
191 if other.root.name == root.name && // same crate-name
192 other.root.disambiguator == root.disambiguator && // same crate-disambiguator
193 other.root.hash != root.hash { // but different SVH
194 span_fatal!(self.sess, span, E0523,
195 "found two different crates with name `{}` that are \
196 not distinguished by differing `-C metadata`. This \
197 will result in symbol conflicts between the two.",
203 fn register_crate(&mut self,
204 root: &Option<CratePaths>,
209 -> (CrateNum, Lrc<cstore::CrateMetadata>) {
210 let crate_root = lib.metadata.get_root();
211 info!("register crate `extern crate {} as {}`", crate_root.name, ident);
212 self.verify_no_symbol_conflicts(span, &crate_root);
214 // Claim this crate number and cache it
215 let cnum = self.cstore.alloc_new_crate_num();
217 // Stash paths for top-most crate locally if necessary.
218 let crate_paths = if root.is_none() {
220 ident: ident.to_string(),
221 dylib: lib.dylib.clone().map(|p| p.0),
222 rlib: lib.rlib.clone().map(|p| p.0),
223 rmeta: lib.rmeta.clone().map(|p| p.0),
228 // Maintain a reference to the top most crate.
229 let root = if root.is_some() { root } else { &crate_paths };
231 let Library { dylib, rlib, rmeta, metadata } = lib;
232 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
234 let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
236 let proc_macros = crate_root.macro_derive_registrar.map(|_| {
237 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
240 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
241 if let Some(proc_macros) = &proc_macros {
242 proc_macro_def_path_table(&crate_root, proc_macros)
244 crate_root.def_path_table.decode((&metadata, self.sess))
248 let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
251 let trait_impls = crate_root
253 .decode((&metadata, self.sess))
254 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
257 let cmeta = cstore::CrateMetadata {
258 name: crate_root.name,
259 extern_crate: Lock::new(None),
260 def_path_table: Lrc::new(def_path_table),
267 dependencies: Lock::new(dependencies),
268 source_map_import_info: RwLock::new(vec![]),
269 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
270 dep_kind: Lock::new(dep_kind),
271 source: cstore::CrateSource {
278 let cmeta = Lrc::new(cmeta);
279 self.cstore.set_crate_data(cnum, cmeta.clone());
283 fn resolve_crate<'b>(
285 root: &'b Option<CratePaths>,
288 hash: Option<&'b Svh>,
289 extra_filename: Option<&'b str>,
292 mut dep_kind: DepKind,
293 ) -> Result<(CrateNum, Lrc<cstore::CrateMetadata>), LoadError<'b>> {
294 info!("resolving crate `extern crate {} as {}`", name, ident);
295 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
296 LoadResult::Previous(cnum)
298 info!("falling back to a load");
299 let mut locate_ctxt = locator::Context {
304 hash: hash.map(|a| &*a),
305 extra_filename: extra_filename,
306 filesearch: self.sess.target_filesearch(path_kind),
307 target: &self.sess.target.target,
308 triple: &self.sess.opts.target_triple,
310 rejected_via_hash: vec![],
311 rejected_via_triple: vec![],
312 rejected_via_kind: vec![],
313 rejected_via_version: vec![],
314 rejected_via_filename: vec![],
315 should_match_name: true,
316 is_proc_macro: Some(false),
317 metadata_loader: &*self.cstore.metadata_loader,
320 self.load(&mut locate_ctxt).or_else(|| {
321 dep_kind = DepKind::UnexportedMacrosOnly;
323 let mut proc_macro_locator = locator::Context {
324 target: &self.sess.host,
325 triple: &TargetTriple::from_triple(config::host_triple()),
326 filesearch: self.sess.host_filesearch(path_kind),
327 rejected_via_hash: vec![],
328 rejected_via_triple: vec![],
329 rejected_via_kind: vec![],
330 rejected_via_version: vec![],
331 rejected_via_filename: vec![],
332 is_proc_macro: Some(true),
336 self.load(&mut proc_macro_locator)
337 }).ok_or_else(move || LoadError::LocatorError(locate_ctxt))?
341 LoadResult::Previous(cnum) => {
342 let data = self.cstore.get_crate_data(cnum);
343 if data.root.macro_derive_registrar.is_some() {
344 dep_kind = DepKind::UnexportedMacrosOnly;
346 data.dep_kind.with_lock(|data_dep_kind| {
347 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
351 LoadResult::Loaded(library) => {
352 Ok(self.register_crate(root, ident, span, library, dep_kind))
357 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
358 let library = locate_ctxt.maybe_load_library_crate()?;
360 // In the case that we're loading a crate, but not matching
361 // against a hash, we could load a crate which has the same hash
362 // as an already loaded crate. If this is the case prevent
363 // duplicates by just using the first crate.
365 // Note that we only do this for target triple crates, though, as we
366 // don't want to match a host crate against an equivalent target one
368 let root = library.metadata.get_root();
369 if locate_ctxt.triple == &self.sess.opts.target_triple {
370 let mut result = LoadResult::Loaded(library);
371 self.cstore.iter_crate_data(|cnum, data| {
372 if data.root.name == root.name && root.hash == data.root.hash {
373 assert!(locate_ctxt.hash.is_none());
374 info!("load success, going to previous cnum: {}", cnum);
375 result = LoadResult::Previous(cnum);
380 Some(LoadResult::Loaded(library))
384 fn update_extern_crate(&mut self,
386 mut extern_crate: ExternCrate,
387 visited: &mut FxHashSet<(CrateNum, bool)>)
389 if !visited.insert((cnum, extern_crate.direct)) { return }
391 let cmeta = self.cstore.get_crate_data(cnum);
392 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
395 // - something over nothing (tuple.0);
396 // - direct extern crate to indirect (tuple.1);
397 // - shorter paths to longer (tuple.2).
401 cmp::Reverse(extern_crate.path_len),
403 let old_rank = match *old_extern_crate {
404 None => (false, false, cmp::Reverse(usize::max_value())),
408 cmp::Reverse(c.path_len),
411 if old_rank >= new_rank {
412 return; // no change needed
415 *old_extern_crate = Some(extern_crate);
416 drop(old_extern_crate);
418 // Propagate the extern crate info to dependencies.
419 extern_crate.direct = false;
420 for &dep_cnum in cmeta.dependencies.borrow().iter() {
421 self.update_extern_crate(dep_cnum, extern_crate, visited);
425 // Go through the crate metadata and load any crates that it references
426 fn resolve_crate_deps(&mut self,
427 root: &Option<CratePaths>,
428 crate_root: &CrateRoot,
429 metadata: &MetadataBlob,
433 -> cstore::CrateNumMap {
434 debug!("resolving deps of external crate");
435 if crate_root.macro_derive_registrar.is_some() {
436 return cstore::CrateNumMap::new();
439 // The map from crate numbers in the crate we're resolving to local crate numbers.
440 // We map 0 and all other holes in the map to our parent crate. The "additional"
441 // self-dependencies should be harmless.
442 ::std::iter::once(krate).chain(crate_root.crate_deps
445 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
447 if dep.kind == DepKind::UnexportedMacrosOnly {
450 let dep_kind = match dep_kind {
451 DepKind::MacrosOnly => DepKind::MacrosOnly,
454 let (local_cnum, ..) = self.resolve_crate(
455 root, dep.name, dep.name, Some(&dep.hash), Some(&dep.extra_filename), span,
456 PathKind::Dependency, dep_kind,
457 ).unwrap_or_else(|err| err.report());
462 fn read_extension_crate(&mut self, span: Span, orig_name: Symbol, rename: Symbol)
464 info!("read extension crate `extern crate {} as {}`", orig_name, rename);
465 let target_triple = &self.sess.opts.target_triple;
466 let host_triple = TargetTriple::from_triple(config::host_triple());
467 let is_cross = target_triple != &host_triple;
468 let mut target_only = false;
469 let mut locate_ctxt = locator::Context {
475 extra_filename: None,
476 filesearch: self.sess.host_filesearch(PathKind::Crate),
477 target: &self.sess.host,
478 triple: &host_triple,
480 rejected_via_hash: vec![],
481 rejected_via_triple: vec![],
482 rejected_via_kind: vec![],
483 rejected_via_version: vec![],
484 rejected_via_filename: vec![],
485 should_match_name: true,
487 metadata_loader: &*self.cstore.metadata_loader,
489 let library = self.load(&mut locate_ctxt).or_else(|| {
493 // Try loading from target crates. This will abort later if we
494 // try to load a plugin registrar function,
497 locate_ctxt.target = &self.sess.target.target;
498 locate_ctxt.triple = target_triple;
499 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
501 self.load(&mut locate_ctxt)
503 let library = match library {
505 None => locate_ctxt.report_errs(),
508 let (dylib, metadata) = match library {
509 LoadResult::Previous(cnum) => {
510 let data = self.cstore.get_crate_data(cnum);
511 (data.source.dylib.clone(), PMDSource::Registered(data))
513 LoadResult::Loaded(library) => {
514 let dylib = library.dylib.clone();
515 let metadata = PMDSource::Owned(library);
522 dylib: dylib.map(|p| p.0),
527 /// Load custom derive macros.
529 /// Note that this is intentionally similar to how we load plugins today,
530 /// but also intentionally separate. Plugins are likely always going to be
531 /// implemented as dynamic libraries, but we have a possible future where
532 /// custom derive (and other macro-1.1 style features) are implemented via
533 /// executables and custom IPC.
534 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
535 -> Vec<(ast::Name, Lrc<SyntaxExtension>)> {
537 use proc_macro::TokenStream;
538 use proc_macro::__internal::Registry;
539 use dynamic_lib::DynamicLibrary;
540 use syntax_ext::deriving::custom::ProcMacroDerive;
541 use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
543 let path = match dylib {
544 Some(dylib) => dylib,
545 None => span_bug!(span, "proc-macro crate not dylib"),
547 // Make sure the path contains a / or the linker will search for it.
548 let path = env::current_dir().unwrap().join(path);
549 let lib = match DynamicLibrary::open(Some(&path)) {
551 Err(err) => self.sess.span_fatal(span, &err),
554 let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator);
555 let registrar = unsafe {
556 let sym = match lib.symbol(&sym) {
558 Err(err) => self.sess.span_fatal(span, &err),
560 mem::transmute::<*mut u8, fn(&mut dyn Registry)>(sym)
564 extensions: Vec<(ast::Name, Lrc<SyntaxExtension>)>,
568 impl Registry for MyRegistrar {
569 fn register_custom_derive(&mut self,
571 expand: fn(TokenStream) -> TokenStream,
572 attributes: &[&'static str]) {
573 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
574 let derive = ProcMacroDerive::new(expand, attrs.clone());
575 let derive = SyntaxExtension::ProcMacroDerive(
576 Box::new(derive), attrs, self.edition
578 self.extensions.push((Symbol::intern(trait_name), Lrc::new(derive)));
581 fn register_attr_proc_macro(&mut self,
583 expand: fn(TokenStream, TokenStream) -> TokenStream) {
584 let expand = SyntaxExtension::AttrProcMacro(
585 Box::new(AttrProcMacro { inner: expand }), self.edition
587 self.extensions.push((Symbol::intern(name), Lrc::new(expand)));
590 fn register_bang_proc_macro(&mut self,
592 expand: fn(TokenStream) -> TokenStream) {
593 let expand = SyntaxExtension::ProcMacro {
594 expander: Box::new(BangProcMacro { inner: expand }),
595 allow_internal_unstable: false,
596 edition: self.edition,
598 self.extensions.push((Symbol::intern(name), Lrc::new(expand)));
602 let mut my_registrar = MyRegistrar { extensions: Vec::new(), edition: root.edition };
603 registrar(&mut my_registrar);
605 // Intentionally leak the dynamic library. We can't ever unload it
606 // since the library can make things that will live arbitrarily long.
608 my_registrar.extensions
611 /// Look for a plugin registrar. Returns library path, crate
612 /// SVH and DefIndex of the registrar function.
613 pub fn find_plugin_registrar(&mut self,
616 -> Option<(PathBuf, CrateDisambiguator)> {
617 let name = Symbol::intern(name);
618 let ekrate = self.read_extension_crate(span, name, name);
620 if ekrate.target_only {
621 // Need to abort before syntax expansion.
622 let message = format!("plugin `{}` is not available for triple `{}` \
625 config::host_triple(),
626 self.sess.opts.target_triple);
627 span_fatal!(self.sess, span, E0456, "{}", &message);
630 let root = ekrate.metadata.get_root();
631 match ekrate.dylib.as_ref() {
633 Some((dylib.to_path_buf(), root.disambiguator))
636 span_err!(self.sess, span, E0457,
637 "plugin `{}` only found in rlib format, but must be available \
640 // No need to abort because the loading code will just ignore this
647 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
648 // If we're only compiling an rlib, then there's no need to select a
649 // panic runtime, so we just skip this section entirely.
650 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
651 *ct != config::CrateType::Rlib
654 info!("panic runtime injection skipped, only generating rlib");
655 self.sess.injected_panic_runtime.set(None);
659 // If we need a panic runtime, we try to find an existing one here. At
660 // the same time we perform some general validation of the DAG we've got
661 // going such as ensuring everything has a compatible panic strategy.
663 // The logic for finding the panic runtime here is pretty much the same
664 // as the allocator case with the only addition that the panic strategy
665 // compilation mode also comes into play.
666 let desired_strategy = self.sess.panic_strategy();
667 let mut runtime_found = false;
668 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
669 "needs_panic_runtime");
671 self.cstore.iter_crate_data(|cnum, data| {
672 needs_panic_runtime = needs_panic_runtime ||
673 data.root.needs_panic_runtime;
674 if data.root.panic_runtime {
675 // Inject a dependency from all #![needs_panic_runtime] to this
676 // #![panic_runtime] crate.
677 self.inject_dependency_if(cnum, "a panic runtime",
678 &|data| data.root.needs_panic_runtime);
679 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
683 // If an explicitly linked and matching panic runtime was found, or if
684 // we just don't need one at all, then we're done here and there's
685 // nothing else to do.
686 if !needs_panic_runtime || runtime_found {
687 self.sess.injected_panic_runtime.set(None);
691 // By this point we know that we (a) need a panic runtime and (b) no
692 // panic runtime was explicitly linked. Here we just load an appropriate
693 // default runtime for our panic strategy and then inject the
696 // We may resolve to an already loaded crate (as the crate may not have
697 // been explicitly linked prior to this) and we may re-inject
698 // dependencies again, but both of those situations are fine.
700 // Also note that we have yet to perform validation of the crate graph
701 // in terms of everyone has a compatible panic runtime format, that's
702 // performed later as part of the `dependency_format` module.
703 let name = match desired_strategy {
704 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
705 PanicStrategy::Abort => Symbol::intern("panic_abort"),
707 info!("panic runtime not found -- loading {}", name);
709 let dep_kind = DepKind::Implicit;
711 self.resolve_crate(&None, name, name, None, None, DUMMY_SP, PathKind::Crate, dep_kind)
712 .unwrap_or_else(|err| err.report());
714 // Sanity check the loaded crate to ensure it is indeed a panic runtime
715 // and the panic strategy is indeed what we thought it was.
716 if !data.root.panic_runtime {
717 self.sess.err(&format!("the crate `{}` is not a panic runtime",
720 if data.root.panic_strategy != desired_strategy {
721 self.sess.err(&format!("the crate `{}` does not have the panic \
723 name, desired_strategy.desc()));
726 self.sess.injected_panic_runtime.set(Some(cnum));
727 self.inject_dependency_if(cnum, "a panic runtime",
728 &|data| data.root.needs_panic_runtime);
731 fn inject_sanitizer_runtime(&mut self) {
732 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
733 // Sanitizers can only be used on some tested platforms with
734 // executables linked to `std`
735 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
736 "x86_64-apple-darwin"];
737 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
738 "x86_64-apple-darwin"];
739 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
740 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
742 let supported_targets = match *sanitizer {
743 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
744 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
745 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
746 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
748 if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
749 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
751 supported_targets.join("` or `")
756 // firstyear 2017 - during testing I was unable to access an OSX machine
757 // to make this work on different crate types. As a result, today I have
758 // only been able to test and support linux as a target.
759 if self.sess.target.target.llvm_target == "x86_64-unknown-linux-gnu" {
760 if !self.sess.crate_types.borrow().iter().all(|ct| {
763 config::CrateType::Staticlib |
764 config::CrateType::Executable => true,
765 // This crate will be compiled with the required
766 // instrumentation pass
767 config::CrateType::Rlib |
768 config::CrateType::Dylib |
769 config::CrateType::Cdylib =>
772 self.sess.err(&format!("Only executables, staticlibs, \
773 cdylibs, dylibs and rlibs can be compiled with \
782 if !self.sess.crate_types.borrow().iter().all(|ct| {
785 config::CrateType::Executable => true,
786 // This crate will be compiled with the required
787 // instrumentation pass
788 config::CrateType::Rlib => false,
790 self.sess.err(&format!("Only executables and rlibs can be \
791 compiled with `-Z sanitizer`"));
800 let mut uses_std = false;
801 self.cstore.iter_crate_data(|_, data| {
802 if data.name == "std" {
808 let name = match *sanitizer {
809 Sanitizer::Address => "rustc_asan",
810 Sanitizer::Leak => "rustc_lsan",
811 Sanitizer::Memory => "rustc_msan",
812 Sanitizer::Thread => "rustc_tsan",
814 info!("loading sanitizer: {}", name);
816 let symbol = Symbol::intern(name);
817 let dep_kind = DepKind::Explicit;
819 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
820 PathKind::Crate, dep_kind)
821 .unwrap_or_else(|err| err.report());
823 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
824 if !data.root.sanitizer_runtime {
825 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
829 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
834 fn inject_profiler_runtime(&mut self) {
835 if self.sess.opts.debugging_opts.profile ||
836 self.sess.opts.debugging_opts.pgo_gen.is_some()
838 info!("loading profiler");
840 let symbol = Symbol::intern("profiler_builtins");
841 let dep_kind = DepKind::Implicit;
843 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
844 PathKind::Crate, dep_kind)
845 .unwrap_or_else(|err| err.report());
847 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
848 if !data.root.profiler_runtime {
849 self.sess.err(&format!("the crate `profiler_builtins` is not \
850 a profiler runtime"));
855 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
856 let has_global_allocator = has_global_allocator(krate);
857 self.sess.has_global_allocator.set(has_global_allocator);
859 // Check to see if we actually need an allocator. This desire comes
860 // about through the `#![needs_allocator]` attribute and is typically
861 // written down in liballoc.
862 let mut needs_allocator = attr::contains_name(&krate.attrs,
864 self.cstore.iter_crate_data(|_, data| {
865 needs_allocator = needs_allocator || data.root.needs_allocator;
867 if !needs_allocator {
868 self.sess.injected_allocator.set(None);
869 self.sess.allocator_kind.set(None);
873 // At this point we've determined that we need an allocator. Let's see
874 // if our compilation session actually needs an allocator based on what
876 let mut need_lib_alloc = false;
877 let mut need_exe_alloc = false;
878 for ct in self.sess.crate_types.borrow().iter() {
880 config::CrateType::Executable => need_exe_alloc = true,
881 config::CrateType::Dylib |
882 config::CrateType::ProcMacro |
883 config::CrateType::Cdylib |
884 config::CrateType::Staticlib => need_lib_alloc = true,
885 config::CrateType::Rlib => {}
888 if !need_lib_alloc && !need_exe_alloc {
889 self.sess.injected_allocator.set(None);
890 self.sess.allocator_kind.set(None);
894 // Ok, we need an allocator. Not only that but we're actually going to
895 // create an artifact that needs one linked in. Let's go find the one
896 // that we're going to link in.
898 // First up we check for global allocators. Look at the crate graph here
899 // and see what's a global allocator, including if we ourselves are a
901 let mut global_allocator = if has_global_allocator {
906 self.cstore.iter_crate_data(|_, data| {
907 if !data.root.has_global_allocator {
910 match global_allocator {
911 Some(Some(other_crate)) => {
912 self.sess.err(&format!("the #[global_allocator] in {} \
913 conflicts with this global \
919 self.sess.err(&format!("the #[global_allocator] in this \
920 crate conflicts with global \
921 allocator in: {}", data.root.name));
923 None => global_allocator = Some(Some(data.root.name)),
926 if global_allocator.is_some() {
927 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
928 self.sess.injected_allocator.set(None);
932 // Ok we haven't found a global allocator but we still need an
933 // allocator. At this point we'll either fall back to the "library
934 // allocator" or the "exe allocator" depending on a few variables. Let's
935 // figure out which one.
937 // Note that here we favor linking to the "library allocator" as much as
938 // possible. If we're not creating rustc's version of libstd
939 // (need_lib_alloc and prefer_dynamic) then we select `None`, and if the
940 // exe allocation crate doesn't exist for this target then we also
942 let exe_allocation_crate_data =
943 if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
950 .exe_allocation_crate
953 // We've determined that we're injecting an "exe allocator" which means
954 // that we're going to load up a whole new crate. An example of this is
955 // that we're producing a normal binary on Linux which means we need to
956 // load the `alloc_jemalloc` crate to link as an allocator.
957 let name = Symbol::intern(name);
958 let (cnum, data) = self.resolve_crate(&None,
966 .unwrap_or_else(|err| err.report());
967 self.sess.injected_allocator.set(Some(cnum));
972 let allocation_crate_data = exe_allocation_crate_data.or_else(|| {
973 // No allocator was injected
974 self.sess.injected_allocator.set(None);
976 if attr::contains_name(&krate.attrs, "default_lib_allocator") {
977 // Prefer self as the allocator if there's a collision
980 // We're not actually going to inject an allocator, we're going to
981 // require that something in our crate graph is the default lib
982 // allocator. This is typically libstd, so this'll rarely be an
984 let mut allocator = None;
985 self.cstore.iter_crate_data(|_, data| {
986 if allocator.is_none() && data.root.has_default_lib_allocator {
987 allocator = Some(data.clone());
993 match allocation_crate_data {
995 // We have an allocator. We detect separately what kind it is, to allow for some
996 // flexibility in misconfiguration.
997 let attrs = data.get_item_attrs(CRATE_DEF_INDEX, self.sess);
998 let kind_interned = attr::first_attr_value_str_by_name(&attrs, "rustc_alloc_kind")
999 .map(Symbol::as_str);
1000 let kind_str = kind_interned
1002 .map(|s| s as &str);
1003 let alloc_kind = match kind_str {
1005 Some("lib") => AllocatorKind::DefaultLib,
1006 Some("exe") => AllocatorKind::DefaultExe,
1008 self.sess.err(&format!("Allocator kind {} not known", other));
1012 self.sess.allocator_kind.set(Some(alloc_kind));
1015 if !attr::contains_name(&krate.attrs, "default_lib_allocator") {
1016 self.sess.err("no global memory allocator found but one is \
1017 required; link to std or \
1018 add #[global_allocator] to a static item \
1019 that implements the GlobalAlloc trait.");
1022 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
1026 fn has_global_allocator(krate: &ast::Crate) -> bool {
1027 struct Finder(bool);
1028 let mut f = Finder(false);
1029 visit::walk_crate(&mut f, krate);
1032 impl<'ast> visit::Visitor<'ast> for Finder {
1033 fn visit_item(&mut self, i: &'ast ast::Item) {
1034 if attr::contains_name(&i.attrs, "global_allocator") {
1037 visit::walk_item(self, i)
1044 fn inject_dependency_if(&self,
1047 needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
1048 // don't perform this validation if the session has errors, as one of
1049 // those errors may indicate a circular dependency which could cause
1050 // this to stack overflow.
1051 if self.sess.has_errors() {
1055 // Before we inject any dependencies, make sure we don't inject a
1056 // circular dependency by validating that this crate doesn't
1057 // transitively depend on any crates satisfying `needs_dep`.
1058 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
1059 let data = self.cstore.get_crate_data(dep);
1060 if needs_dep(&data) {
1061 self.sess.err(&format!("the crate `{}` cannot depend \
1062 on a crate that needs {}, but \
1063 it depends on `{}`",
1064 self.cstore.get_crate_data(krate).root.name,
1070 // All crates satisfying `needs_dep` do not explicitly depend on the
1071 // crate provided for this compile, but in order for this compilation to
1072 // be successfully linked we need to inject a dependency (to order the
1073 // crates on the command line correctly).
1074 self.cstore.iter_crate_data(|cnum, data| {
1075 if !needs_dep(data) {
1079 info!("injecting a dep from {} to {}", cnum, krate);
1080 data.dependencies.borrow_mut().push(krate);
1085 impl<'a> CrateLoader<'a> {
1086 pub fn postprocess(&mut self, krate: &ast::Crate) {
1087 // inject the sanitizer runtime before the allocator runtime because all
1088 // sanitizers force the use of the `alloc_system` allocator
1089 self.inject_sanitizer_runtime();
1090 self.inject_profiler_runtime();
1091 self.inject_allocator_crate(krate);
1092 self.inject_panic_runtime(krate);
1094 if log_enabled!(log::Level::Info) {
1095 dump_crates(&self.cstore);
1099 pub fn process_extern_crate(
1100 &mut self, item: &ast::Item, definitions: &Definitions,
1103 ast::ItemKind::ExternCrate(orig_name) => {
1104 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
1105 item.ident, orig_name);
1106 let orig_name = match orig_name {
1107 Some(orig_name) => {
1108 validate_crate_name(Some(self.sess), &orig_name.as_str(),
1112 None => item.ident.name,
1114 let dep_kind = if attr::contains_name(&item.attrs, "no_link") {
1115 DepKind::UnexportedMacrosOnly
1120 let (cnum, ..) = self.resolve_crate(
1121 &None, item.ident.name, orig_name, None, None,
1122 item.span, PathKind::Crate, dep_kind,
1123 ).unwrap_or_else(|err| err.report());
1125 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1126 let path_len = definitions.def_path(def_id.index).data.len();
1127 self.update_extern_crate(
1130 src: ExternCrateSource::Extern(def_id),
1137 self.cstore.add_extern_mod_stmt_cnum(item.id, cnum);
1144 pub fn process_path_extern(
1149 let cnum = self.resolve_crate(
1150 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1151 ).unwrap_or_else(|err| err.report()).0;
1153 self.update_extern_crate(
1156 src: ExternCrateSource::Path,
1158 // to have the least priority in `update_extern_crate`
1159 path_len: usize::max_value(),
1168 pub fn maybe_process_path_extern(
1172 ) -> Option<CrateNum> {
1173 let cnum = self.resolve_crate(
1174 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1177 self.update_extern_crate(
1180 src: ExternCrateSource::Path,
1182 // to have the least priority in `update_extern_crate`
1183 path_len: usize::max_value(),