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;
16 use rustc_data_structures::sync::{Lrc, RwLock, Lock};
18 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX};
19 use rustc::hir::svh::Svh;
20 use rustc::middle::allocator::AllocatorKind;
21 use rustc::middle::cstore::DepKind;
22 use rustc::mir::interpret::AllocDecodingState;
23 use rustc::session::{Session, CrateDisambiguator};
24 use rustc::session::config::{Sanitizer, self};
25 use rustc_target::spec::{PanicStrategy, TargetTriple};
26 use rustc::session::search_paths::PathKind;
27 use rustc::middle::cstore::{ExternCrate, ExternCrateSource};
28 use rustc::util::common::record_time;
29 use rustc::util::nodemap::FxHashSet;
30 use rustc::hir::map::Definitions;
32 use rustc_metadata_utils::validate_crate_name;
35 use std::path::PathBuf;
40 use syntax::edition::Edition;
41 use syntax::ext::base::SyntaxExtension;
42 use syntax::symbol::Symbol;
44 use syntax_pos::{Span, DUMMY_SP};
48 pub dylib: Option<(PathBuf, PathKind)>,
49 pub rlib: Option<(PathBuf, PathKind)>,
50 pub rmeta: Option<(PathBuf, PathKind)>,
51 pub metadata: MetadataBlob,
54 pub struct CrateLoader<'a> {
55 pub sess: &'a Session,
57 local_crate_name: Symbol,
60 fn dump_crates(cstore: &CStore) {
61 info!("resolved crates:");
62 cstore.iter_crate_data(|_, data| {
63 info!(" name: {}", data.root.name);
64 info!(" cnum: {}", data.cnum);
65 info!(" hash: {}", data.root.hash);
66 info!(" reqd: {:?}", *data.dep_kind.lock());
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()));
74 // Extra info about a crate loaded for plugins or exported macros.
75 struct ExtensionCrate {
77 dylib: Option<PathBuf>,
82 Registered(Lrc<cstore::CrateMetadata>),
86 impl Deref for PMDSource {
87 type Target = MetadataBlob;
89 fn deref(&self) -> &MetadataBlob {
91 PMDSource::Registered(ref cmd) => &cmd.blob,
92 PMDSource::Owned(ref lib) => &lib.metadata
102 impl<'a> CrateLoader<'a> {
103 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
107 local_crate_name: Symbol::intern(local_crate_name),
111 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
112 -> Option<CrateNum> {
114 self.cstore.iter_crate_data(|cnum, data| {
115 if data.name != name { return }
118 Some(hash) if *hash == data.root.hash => { ret = Some(cnum); return }
123 // When the hash is None we're dealing with a top-level dependency
124 // in which case we may have a specification on the command line for
125 // this library. Even though an upstream library may have loaded
126 // something of the same name, we have to make sure it was loaded
127 // from the exact same location as well.
129 // We're also sure to compare *paths*, not actual byte slices. The
130 // `source` stores paths which are normalized which may be different
131 // from the strings on the command line.
132 let source = &self.cstore.get_crate_data(cnum).source;
133 if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
134 let found = locs.iter().any(|l| {
135 let l = fs::canonicalize(l).ok();
136 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
137 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
145 // Alright, so we've gotten this far which means that `data` has the
146 // right name, we don't have a hash, and we don't have a --extern
147 // pointing for ourselves. We're still not quite yet done because we
148 // have to make sure that this crate was found in the crate lookup
149 // path (this is a top-level dependency) as we don't want to
150 // implicitly load anything inside the dependency lookup path.
151 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
152 .or(source.rmeta.as_ref())
153 .expect("No sources for crate").1;
154 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
161 fn verify_no_symbol_conflicts(&self,
164 // Check for (potential) conflicts with the local crate
165 if self.local_crate_name == root.name &&
166 self.sess.local_crate_disambiguator() == root.disambiguator {
167 span_fatal!(self.sess, span, E0519,
168 "the current crate is indistinguishable from one of its \
169 dependencies: it has the same crate-name `{}` and was \
170 compiled with the same `-C metadata` arguments. This \
171 will result in symbol conflicts between the two.",
175 // Check for conflicts with any crate loaded so far
176 self.cstore.iter_crate_data(|_, other| {
177 if other.root.name == root.name && // same crate-name
178 other.root.disambiguator == root.disambiguator && // same crate-disambiguator
179 other.root.hash != root.hash { // but different SVH
180 span_fatal!(self.sess, span, E0523,
181 "found two different crates with name `{}` that are \
182 not distinguished by differing `-C metadata`. This \
183 will result in symbol conflicts between the two.",
189 fn register_crate(&mut self,
190 root: &Option<CratePaths>,
195 -> (CrateNum, Lrc<cstore::CrateMetadata>) {
196 let crate_root = lib.metadata.get_root();
197 info!("register crate `extern crate {} as {}`", crate_root.name, ident);
198 self.verify_no_symbol_conflicts(span, &crate_root);
200 // Claim this crate number and cache it
201 let cnum = self.cstore.alloc_new_crate_num();
203 // Stash paths for top-most crate locally if necessary.
204 let crate_paths = if root.is_none() {
206 ident: ident.to_string(),
207 dylib: lib.dylib.clone().map(|p| p.0),
208 rlib: lib.rlib.clone().map(|p| p.0),
209 rmeta: lib.rmeta.clone().map(|p| p.0),
214 // Maintain a reference to the top most crate.
215 let root = if root.is_some() { root } else { &crate_paths };
217 let Library { dylib, rlib, rmeta, metadata } = lib;
218 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
220 let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
222 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
223 crate_root.def_path_table.decode((&metadata, self.sess))
226 let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
229 let trait_impls = crate_root
231 .decode((&metadata, self.sess))
232 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
235 let cmeta = cstore::CrateMetadata {
236 name: crate_root.name,
237 extern_crate: Lock::new(None),
238 def_path_table: Lrc::new(def_path_table),
240 proc_macros: crate_root.macro_derive_registrar.map(|_| {
241 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
247 dependencies: Lock::new(dependencies),
248 codemap_import_info: RwLock::new(vec![]),
249 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
250 dep_kind: Lock::new(dep_kind),
251 source: cstore::CrateSource {
258 let cmeta = Lrc::new(cmeta);
259 self.cstore.set_crate_data(cnum, cmeta.clone());
263 fn resolve_crate(&mut self,
264 root: &Option<CratePaths>,
268 extra_filename: Option<&str>,
271 mut dep_kind: DepKind)
272 -> (CrateNum, Lrc<cstore::CrateMetadata>) {
273 info!("resolving crate `extern crate {} as {}`", name, ident);
274 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
275 LoadResult::Previous(cnum)
277 info!("falling back to a load");
278 let mut locate_ctxt = locator::Context {
283 hash: hash.map(|a| &*a),
284 extra_filename: extra_filename,
285 filesearch: self.sess.target_filesearch(path_kind),
286 target: &self.sess.target.target,
287 triple: &self.sess.opts.target_triple,
289 rejected_via_hash: vec![],
290 rejected_via_triple: vec![],
291 rejected_via_kind: vec![],
292 rejected_via_version: vec![],
293 rejected_via_filename: vec![],
294 should_match_name: true,
295 is_proc_macro: Some(false),
296 metadata_loader: &*self.cstore.metadata_loader,
299 self.load(&mut locate_ctxt).or_else(|| {
300 dep_kind = DepKind::UnexportedMacrosOnly;
302 let mut proc_macro_locator = locator::Context {
303 target: &self.sess.host,
304 triple: &TargetTriple::from_triple(config::host_triple()),
305 filesearch: self.sess.host_filesearch(path_kind),
306 rejected_via_hash: vec![],
307 rejected_via_triple: vec![],
308 rejected_via_kind: vec![],
309 rejected_via_version: vec![],
310 rejected_via_filename: vec![],
311 is_proc_macro: Some(true),
315 self.load(&mut proc_macro_locator)
316 }).unwrap_or_else(|| locate_ctxt.report_errs())
320 LoadResult::Previous(cnum) => {
321 let data = self.cstore.get_crate_data(cnum);
322 if data.root.macro_derive_registrar.is_some() {
323 dep_kind = DepKind::UnexportedMacrosOnly;
325 data.dep_kind.with_lock(|data_dep_kind| {
326 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
330 LoadResult::Loaded(library) => {
331 self.register_crate(root, ident, span, library, dep_kind)
336 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
337 let library = locate_ctxt.maybe_load_library_crate()?;
339 // In the case that we're loading a crate, but not matching
340 // against a hash, we could load a crate which has the same hash
341 // as an already loaded crate. If this is the case prevent
342 // duplicates by just using the first crate.
344 // Note that we only do this for target triple crates, though, as we
345 // don't want to match a host crate against an equivalent target one
347 let root = library.metadata.get_root();
348 if locate_ctxt.triple == &self.sess.opts.target_triple {
349 let mut result = LoadResult::Loaded(library);
350 self.cstore.iter_crate_data(|cnum, data| {
351 if data.root.name == root.name && root.hash == data.root.hash {
352 assert!(locate_ctxt.hash.is_none());
353 info!("load success, going to previous cnum: {}", cnum);
354 result = LoadResult::Previous(cnum);
359 Some(LoadResult::Loaded(library))
363 fn update_extern_crate(&mut self,
365 mut extern_crate: ExternCrate,
366 visited: &mut FxHashSet<(CrateNum, bool)>)
368 if !visited.insert((cnum, extern_crate.direct)) { return }
370 let cmeta = self.cstore.get_crate_data(cnum);
371 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
374 // - something over nothing (tuple.0);
375 // - direct extern crate to indirect (tuple.1);
376 // - shorter paths to longer (tuple.2).
380 cmp::Reverse(extern_crate.path_len),
382 let old_rank = match *old_extern_crate {
383 None => (false, false, cmp::Reverse(usize::max_value())),
387 cmp::Reverse(c.path_len),
390 if old_rank >= new_rank {
391 return; // no change needed
394 *old_extern_crate = Some(extern_crate);
395 drop(old_extern_crate);
397 // Propagate the extern crate info to dependencies.
398 extern_crate.direct = false;
399 for &dep_cnum in cmeta.dependencies.borrow().iter() {
400 self.update_extern_crate(dep_cnum, extern_crate, visited);
404 // Go through the crate metadata and load any crates that it references
405 fn resolve_crate_deps(&mut self,
406 root: &Option<CratePaths>,
407 crate_root: &CrateRoot,
408 metadata: &MetadataBlob,
412 -> cstore::CrateNumMap {
413 debug!("resolving deps of external crate");
414 if crate_root.macro_derive_registrar.is_some() {
415 return cstore::CrateNumMap::new();
418 // The map from crate numbers in the crate we're resolving to local crate numbers.
419 // We map 0 and all other holes in the map to our parent crate. The "additional"
420 // self-dependencies should be harmless.
421 ::std::iter::once(krate).chain(crate_root.crate_deps
424 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
426 if dep.kind == DepKind::UnexportedMacrosOnly {
429 let dep_kind = match dep_kind {
430 DepKind::MacrosOnly => DepKind::MacrosOnly,
433 let (local_cnum, ..) = self.resolve_crate(
434 root, dep.name, dep.name, Some(&dep.hash), Some(&dep.extra_filename), span,
435 PathKind::Dependency, dep_kind,
441 fn read_extension_crate(&mut self, span: Span, orig_name: Symbol, rename: Symbol)
443 info!("read extension crate `extern crate {} as {}`", orig_name, rename);
444 let target_triple = &self.sess.opts.target_triple;
445 let host_triple = TargetTriple::from_triple(config::host_triple());
446 let is_cross = target_triple != &host_triple;
447 let mut target_only = false;
448 let mut locate_ctxt = locator::Context {
454 extra_filename: None,
455 filesearch: self.sess.host_filesearch(PathKind::Crate),
456 target: &self.sess.host,
457 triple: &host_triple,
459 rejected_via_hash: vec![],
460 rejected_via_triple: vec![],
461 rejected_via_kind: vec![],
462 rejected_via_version: vec![],
463 rejected_via_filename: vec![],
464 should_match_name: true,
466 metadata_loader: &*self.cstore.metadata_loader,
468 let library = self.load(&mut locate_ctxt).or_else(|| {
472 // Try loading from target crates. This will abort later if we
473 // try to load a plugin registrar function,
476 locate_ctxt.target = &self.sess.target.target;
477 locate_ctxt.triple = target_triple;
478 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
480 self.load(&mut locate_ctxt)
482 let library = match library {
484 None => locate_ctxt.report_errs(),
487 let (dylib, metadata) = match library {
488 LoadResult::Previous(cnum) => {
489 let data = self.cstore.get_crate_data(cnum);
490 (data.source.dylib.clone(), PMDSource::Registered(data))
492 LoadResult::Loaded(library) => {
493 let dylib = library.dylib.clone();
494 let metadata = PMDSource::Owned(library);
501 dylib: dylib.map(|p| p.0),
506 /// Load custom derive macros.
508 /// Note that this is intentionally similar to how we load plugins today,
509 /// but also intentionally separate. Plugins are likely always going to be
510 /// implemented as dynamic libraries, but we have a possible future where
511 /// custom derive (and other macro-1.1 style features) are implemented via
512 /// executables and custom IPC.
513 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
514 -> Vec<(ast::Name, Lrc<SyntaxExtension>)> {
516 use proc_macro::TokenStream;
517 use proc_macro::__internal::Registry;
518 use dynamic_lib::DynamicLibrary;
519 use syntax_ext::deriving::custom::ProcMacroDerive;
520 use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
522 let path = match dylib {
523 Some(dylib) => dylib,
524 None => span_bug!(span, "proc-macro crate not dylib"),
526 // Make sure the path contains a / or the linker will search for it.
527 let path = env::current_dir().unwrap().join(path);
528 let lib = match DynamicLibrary::open(Some(&path)) {
530 Err(err) => self.sess.span_fatal(span, &err),
533 let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator);
534 let registrar = unsafe {
535 let sym = match lib.symbol(&sym) {
537 Err(err) => self.sess.span_fatal(span, &err),
539 mem::transmute::<*mut u8, fn(&mut dyn Registry)>(sym)
543 extensions: Vec<(ast::Name, Lrc<SyntaxExtension>)>,
547 impl Registry for MyRegistrar {
548 fn register_custom_derive(&mut self,
550 expand: fn(TokenStream) -> TokenStream,
551 attributes: &[&'static str]) {
552 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
553 let derive = ProcMacroDerive::new(expand, attrs.clone());
554 let derive = SyntaxExtension::ProcMacroDerive(
555 Box::new(derive), attrs, self.edition
557 self.extensions.push((Symbol::intern(trait_name), Lrc::new(derive)));
560 fn register_attr_proc_macro(&mut self,
562 expand: fn(TokenStream, TokenStream) -> TokenStream) {
563 let expand = SyntaxExtension::AttrProcMacro(
564 Box::new(AttrProcMacro { inner: expand }), self.edition
566 self.extensions.push((Symbol::intern(name), Lrc::new(expand)));
569 fn register_bang_proc_macro(&mut self,
571 expand: fn(TokenStream) -> TokenStream) {
572 let expand = SyntaxExtension::ProcMacro {
573 expander: Box::new(BangProcMacro { inner: expand }),
574 allow_internal_unstable: false,
575 edition: self.edition,
577 self.extensions.push((Symbol::intern(name), Lrc::new(expand)));
581 let mut my_registrar = MyRegistrar { extensions: Vec::new(), edition: root.edition };
582 registrar(&mut my_registrar);
584 // Intentionally leak the dynamic library. We can't ever unload it
585 // since the library can make things that will live arbitrarily long.
587 my_registrar.extensions
590 /// Look for a plugin registrar. Returns library path, crate
591 /// SVH and DefIndex of the registrar function.
592 pub fn find_plugin_registrar(&mut self,
595 -> Option<(PathBuf, CrateDisambiguator)> {
596 let name = Symbol::intern(name);
597 let ekrate = self.read_extension_crate(span, name, name);
599 if ekrate.target_only {
600 // Need to abort before syntax expansion.
601 let message = format!("plugin `{}` is not available for triple `{}` \
604 config::host_triple(),
605 self.sess.opts.target_triple);
606 span_fatal!(self.sess, span, E0456, "{}", &message);
609 let root = ekrate.metadata.get_root();
610 match ekrate.dylib.as_ref() {
612 Some((dylib.to_path_buf(), root.disambiguator))
615 span_err!(self.sess, span, E0457,
616 "plugin `{}` only found in rlib format, but must be available \
619 // No need to abort because the loading code will just ignore this
626 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
627 // If we're only compiling an rlib, then there's no need to select a
628 // panic runtime, so we just skip this section entirely.
629 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
630 *ct != config::CrateType::Rlib
633 info!("panic runtime injection skipped, only generating rlib");
634 self.sess.injected_panic_runtime.set(None);
638 // If we need a panic runtime, we try to find an existing one here. At
639 // the same time we perform some general validation of the DAG we've got
640 // going such as ensuring everything has a compatible panic strategy.
642 // The logic for finding the panic runtime here is pretty much the same
643 // as the allocator case with the only addition that the panic strategy
644 // compilation mode also comes into play.
645 let desired_strategy = self.sess.panic_strategy();
646 let mut runtime_found = false;
647 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
648 "needs_panic_runtime");
650 self.cstore.iter_crate_data(|cnum, data| {
651 needs_panic_runtime = needs_panic_runtime ||
652 data.root.needs_panic_runtime;
653 if data.root.panic_runtime {
654 // Inject a dependency from all #![needs_panic_runtime] to this
655 // #![panic_runtime] crate.
656 self.inject_dependency_if(cnum, "a panic runtime",
657 &|data| data.root.needs_panic_runtime);
658 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
662 // If an explicitly linked and matching panic runtime was found, or if
663 // we just don't need one at all, then we're done here and there's
664 // nothing else to do.
665 if !needs_panic_runtime || runtime_found {
666 self.sess.injected_panic_runtime.set(None);
670 // By this point we know that we (a) need a panic runtime and (b) no
671 // panic runtime was explicitly linked. Here we just load an appropriate
672 // default runtime for our panic strategy and then inject the
675 // We may resolve to an already loaded crate (as the crate may not have
676 // been explicitly linked prior to this) and we may re-inject
677 // dependencies again, but both of those situations are fine.
679 // Also note that we have yet to perform validation of the crate graph
680 // in terms of everyone has a compatible panic runtime format, that's
681 // performed later as part of the `dependency_format` module.
682 let name = match desired_strategy {
683 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
684 PanicStrategy::Abort => Symbol::intern("panic_abort"),
686 info!("panic runtime not found -- loading {}", name);
688 let dep_kind = DepKind::Implicit;
690 self.resolve_crate(&None, name, name, None, None, DUMMY_SP, PathKind::Crate, dep_kind);
692 // Sanity check the loaded crate to ensure it is indeed a panic runtime
693 // and the panic strategy is indeed what we thought it was.
694 if !data.root.panic_runtime {
695 self.sess.err(&format!("the crate `{}` is not a panic runtime",
698 if data.root.panic_strategy != desired_strategy {
699 self.sess.err(&format!("the crate `{}` does not have the panic \
701 name, desired_strategy.desc()));
704 self.sess.injected_panic_runtime.set(Some(cnum));
705 self.inject_dependency_if(cnum, "a panic runtime",
706 &|data| data.root.needs_panic_runtime);
709 fn inject_sanitizer_runtime(&mut self) {
710 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
711 // Sanitizers can only be used on some tested platforms with
712 // executables linked to `std`
713 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
714 "x86_64-apple-darwin"];
715 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
716 "x86_64-apple-darwin"];
717 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
718 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
720 let supported_targets = match *sanitizer {
721 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
722 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
723 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
724 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
726 if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
727 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
729 supported_targets.join("` or `")
734 // firstyear 2017 - during testing I was unable to access an OSX machine
735 // to make this work on different crate types. As a result, today I have
736 // only been able to test and support linux as a target.
737 if self.sess.target.target.llvm_target == "x86_64-unknown-linux-gnu" {
738 if !self.sess.crate_types.borrow().iter().all(|ct| {
741 config::CrateType::Staticlib |
742 config::CrateType::Executable => true,
743 // This crate will be compiled with the required
744 // instrumentation pass
745 config::CrateType::Rlib |
746 config::CrateType::Dylib |
747 config::CrateType::Cdylib =>
750 self.sess.err(&format!("Only executables, staticlibs, \
751 cdylibs, dylibs and rlibs can be compiled with \
760 if !self.sess.crate_types.borrow().iter().all(|ct| {
763 config::CrateType::Executable => true,
764 // This crate will be compiled with the required
765 // instrumentation pass
766 config::CrateType::Rlib => false,
768 self.sess.err(&format!("Only executables and rlibs can be \
769 compiled with `-Z sanitizer`"));
778 let mut uses_std = false;
779 self.cstore.iter_crate_data(|_, data| {
780 if data.name == "std" {
786 let name = match *sanitizer {
787 Sanitizer::Address => "rustc_asan",
788 Sanitizer::Leak => "rustc_lsan",
789 Sanitizer::Memory => "rustc_msan",
790 Sanitizer::Thread => "rustc_tsan",
792 info!("loading sanitizer: {}", name);
794 let symbol = Symbol::intern(name);
795 let dep_kind = DepKind::Explicit;
797 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
798 PathKind::Crate, dep_kind);
800 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
801 if !data.root.sanitizer_runtime {
802 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
806 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
811 fn inject_profiler_runtime(&mut self) {
812 if self.sess.opts.debugging_opts.profile ||
813 self.sess.opts.debugging_opts.pgo_gen.is_some()
815 info!("loading profiler");
817 let symbol = Symbol::intern("profiler_builtins");
818 let dep_kind = DepKind::Implicit;
820 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
821 PathKind::Crate, dep_kind);
823 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
824 if !data.root.profiler_runtime {
825 self.sess.err(&format!("the crate `profiler_builtins` is not \
826 a profiler runtime"));
831 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
832 let has_global_allocator = has_global_allocator(krate);
833 self.sess.has_global_allocator.set(has_global_allocator);
835 // Check to see if we actually need an allocator. This desire comes
836 // about through the `#![needs_allocator]` attribute and is typically
837 // written down in liballoc.
838 let mut needs_allocator = attr::contains_name(&krate.attrs,
840 self.cstore.iter_crate_data(|_, data| {
841 needs_allocator = needs_allocator || data.root.needs_allocator;
843 if !needs_allocator {
844 self.sess.injected_allocator.set(None);
845 self.sess.allocator_kind.set(None);
849 // At this point we've determined that we need an allocator. Let's see
850 // if our compilation session actually needs an allocator based on what
852 let mut need_lib_alloc = false;
853 let mut need_exe_alloc = false;
854 for ct in self.sess.crate_types.borrow().iter() {
856 config::CrateType::Executable => need_exe_alloc = true,
857 config::CrateType::Dylib |
858 config::CrateType::ProcMacro |
859 config::CrateType::Cdylib |
860 config::CrateType::Staticlib => need_lib_alloc = true,
861 config::CrateType::Rlib => {}
864 if !need_lib_alloc && !need_exe_alloc {
865 self.sess.injected_allocator.set(None);
866 self.sess.allocator_kind.set(None);
870 // Ok, we need an allocator. Not only that but we're actually going to
871 // create an artifact that needs one linked in. Let's go find the one
872 // that we're going to link in.
874 // First up we check for global allocators. Look at the crate graph here
875 // and see what's a global allocator, including if we ourselves are a
877 let mut global_allocator = if has_global_allocator {
882 self.cstore.iter_crate_data(|_, data| {
883 if !data.root.has_global_allocator {
886 match global_allocator {
887 Some(Some(other_crate)) => {
888 self.sess.err(&format!("the #[global_allocator] in {} \
889 conflicts with this global \
895 self.sess.err(&format!("the #[global_allocator] in this \
896 crate conflicts with global \
897 allocator in: {}", data.root.name));
899 None => global_allocator = Some(Some(data.root.name)),
902 if global_allocator.is_some() {
903 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
904 self.sess.injected_allocator.set(None);
908 // Ok we haven't found a global allocator but we still need an
909 // allocator. At this point we'll either fall back to the "library
910 // allocator" or the "exe allocator" depending on a few variables. Let's
911 // figure out which one.
913 // Note that here we favor linking to the "library allocator" as much as
914 // possible. If we're not creating rustc's version of libstd
915 // (need_lib_alloc and prefer_dynamic) then we select `None`, and if the
916 // exe allocation crate doesn't exist for this target then we also
918 let exe_allocation_crate_data =
919 if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
926 .exe_allocation_crate
929 // We've determined that we're injecting an "exe allocator" which means
930 // that we're going to load up a whole new crate. An example of this is
931 // that we're producing a normal binary on Linux which means we need to
932 // load the `alloc_jemalloc` crate to link as an allocator.
933 let name = Symbol::intern(name);
934 let (cnum, data) = self.resolve_crate(&None,
942 self.sess.injected_allocator.set(Some(cnum));
947 let allocation_crate_data = exe_allocation_crate_data.or_else(|| {
948 // No allocator was injected
949 self.sess.injected_allocator.set(None);
951 if attr::contains_name(&krate.attrs, "default_lib_allocator") {
952 // Prefer self as the allocator if there's a collision
955 // We're not actually going to inject an allocator, we're going to
956 // require that something in our crate graph is the default lib
957 // allocator. This is typically libstd, so this'll rarely be an
959 let mut allocator = None;
960 self.cstore.iter_crate_data(|_, data| {
961 if allocator.is_none() && data.root.has_default_lib_allocator {
962 allocator = Some(data.clone());
968 match allocation_crate_data {
970 // We have an allocator. We detect separately what kind it is, to allow for some
971 // flexibility in misconfiguration.
972 let attrs = data.get_item_attrs(CRATE_DEF_INDEX, self.sess);
973 let kind_interned = attr::first_attr_value_str_by_name(&attrs, "rustc_alloc_kind")
974 .map(Symbol::as_str);
975 let kind_str = kind_interned
978 let alloc_kind = match kind_str {
980 Some("lib") => AllocatorKind::DefaultLib,
981 Some("exe") => AllocatorKind::DefaultExe,
983 self.sess.err(&format!("Allocator kind {} not known", other));
987 self.sess.allocator_kind.set(Some(alloc_kind));
990 if !attr::contains_name(&krate.attrs, "default_lib_allocator") {
991 self.sess.err("no global memory allocator found but one is \
992 required; link to std or \
993 add #[global_allocator] to a static item \
994 that implements the GlobalAlloc trait.");
997 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
1001 fn has_global_allocator(krate: &ast::Crate) -> bool {
1002 struct Finder(bool);
1003 let mut f = Finder(false);
1004 visit::walk_crate(&mut f, krate);
1007 impl<'ast> visit::Visitor<'ast> for Finder {
1008 fn visit_item(&mut self, i: &'ast ast::Item) {
1009 if attr::contains_name(&i.attrs, "global_allocator") {
1012 visit::walk_item(self, i)
1019 fn inject_dependency_if(&self,
1022 needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
1023 // don't perform this validation if the session has errors, as one of
1024 // those errors may indicate a circular dependency which could cause
1025 // this to stack overflow.
1026 if self.sess.has_errors() {
1030 // Before we inject any dependencies, make sure we don't inject a
1031 // circular dependency by validating that this crate doesn't
1032 // transitively depend on any crates satisfying `needs_dep`.
1033 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
1034 let data = self.cstore.get_crate_data(dep);
1035 if needs_dep(&data) {
1036 self.sess.err(&format!("the crate `{}` cannot depend \
1037 on a crate that needs {}, but \
1038 it depends on `{}`",
1039 self.cstore.get_crate_data(krate).root.name,
1045 // All crates satisfying `needs_dep` do not explicitly depend on the
1046 // crate provided for this compile, but in order for this compilation to
1047 // be successfully linked we need to inject a dependency (to order the
1048 // crates on the command line correctly).
1049 self.cstore.iter_crate_data(|cnum, data| {
1050 if !needs_dep(data) {
1054 info!("injecting a dep from {} to {}", cnum, krate);
1055 data.dependencies.borrow_mut().push(krate);
1060 impl<'a> CrateLoader<'a> {
1061 pub fn postprocess(&mut self, krate: &ast::Crate) {
1062 // inject the sanitizer runtime before the allocator runtime because all
1063 // sanitizers force the use of the `alloc_system` allocator
1064 self.inject_sanitizer_runtime();
1065 self.inject_profiler_runtime();
1066 self.inject_allocator_crate(krate);
1067 self.inject_panic_runtime(krate);
1069 if log_enabled!(log::Level::Info) {
1070 dump_crates(&self.cstore);
1074 pub fn process_extern_crate(
1075 &mut self, item: &ast::Item, definitions: &Definitions,
1078 ast::ItemKind::ExternCrate(orig_name) => {
1079 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
1080 item.ident, orig_name);
1081 let orig_name = match orig_name {
1082 Some(orig_name) => {
1083 validate_crate_name(Some(self.sess), &orig_name.as_str(),
1087 None => item.ident.name,
1089 let dep_kind = if attr::contains_name(&item.attrs, "no_link") {
1090 DepKind::UnexportedMacrosOnly
1095 let (cnum, ..) = self.resolve_crate(
1096 &None, item.ident.name, orig_name, None, None,
1097 item.span, PathKind::Crate, dep_kind,
1100 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1101 let path_len = definitions.def_path(def_id.index).data.len();
1102 self.update_extern_crate(
1105 src: ExternCrateSource::Extern(def_id),
1112 self.cstore.add_extern_mod_stmt_cnum(item.id, cnum);
1119 pub fn process_path_extern(
1124 let cnum = self.resolve_crate(
1125 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1128 self.update_extern_crate(
1131 src: ExternCrateSource::Path,
1133 // to have the least priority in `update_extern_crate`
1134 path_len: usize::max_value(),
1143 pub fn process_use_extern(
1148 definitions: &Definitions,
1150 let cnum = self.resolve_crate(
1151 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1154 let def_id = definitions.opt_local_def_id(id).unwrap();
1155 let path_len = definitions.def_path(def_id.index).data.len();
1157 self.update_extern_crate(
1160 src: ExternCrateSource::Use,