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;
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;
34 use std::path::PathBuf;
39 use syntax::ext::base::SyntaxExtension;
40 use syntax::symbol::Symbol;
42 use syntax_pos::{Span, DUMMY_SP};
46 pub dylib: Option<(PathBuf, PathKind)>,
47 pub rlib: Option<(PathBuf, PathKind)>,
48 pub rmeta: Option<(PathBuf, PathKind)>,
49 pub metadata: MetadataBlob,
52 pub struct CrateLoader<'a> {
53 pub sess: &'a Session,
55 local_crate_name: Symbol,
58 fn dump_crates(cstore: &CStore) {
59 info!("resolved crates:");
60 cstore.iter_crate_data(|_, data| {
61 info!(" name: {}", data.root.name);
62 info!(" cnum: {}", data.cnum);
63 info!(" hash: {}", data.root.hash);
64 info!(" reqd: {:?}", *data.dep_kind.lock());
65 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
66 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
67 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
68 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
72 // Extra info about a crate loaded for plugins or exported macros.
73 struct ExtensionCrate {
75 dylib: Option<PathBuf>,
80 Registered(Lrc<cstore::CrateMetadata>),
84 impl Deref for PMDSource {
85 type Target = MetadataBlob;
87 fn deref(&self) -> &MetadataBlob {
89 PMDSource::Registered(ref cmd) => &cmd.blob,
90 PMDSource::Owned(ref lib) => &lib.metadata
101 LocatorError(locator::Context<'a>),
104 impl<'a> LoadError<'a> {
105 fn report(self) -> ! {
107 LoadError::LocatorError(mut locate_ctxt) => locate_ctxt.report_errs(),
112 impl<'a> CrateLoader<'a> {
113 pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
117 local_crate_name: Symbol::intern(local_crate_name),
121 fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
122 -> Option<CrateNum> {
124 self.cstore.iter_crate_data(|cnum, data| {
125 if data.name != name { return }
128 Some(hash) if *hash == data.root.hash => { ret = Some(cnum); return }
133 // When the hash is None we're dealing with a top-level dependency
134 // in which case we may have a specification on the command line for
135 // this library. Even though an upstream library may have loaded
136 // something of the same name, we have to make sure it was loaded
137 // from the exact same location as well.
139 // We're also sure to compare *paths*, not actual byte slices. The
140 // `source` stores paths which are normalized which may be different
141 // from the strings on the command line.
142 let source = &self.cstore.get_crate_data(cnum).source;
143 if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
144 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
145 let found = locs.iter().filter_map(|l| l.as_ref()).any(|l| {
146 let l = fs::canonicalize(l).ok();
147 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
148 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
156 // Alright, so we've gotten this far which means that `data` has the
157 // right name, we don't have a hash, and we don't have a --extern
158 // pointing for ourselves. We're still not quite yet done because we
159 // have to make sure that this crate was found in the crate lookup
160 // path (this is a top-level dependency) as we don't want to
161 // implicitly load anything inside the dependency lookup path.
162 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
163 .or(source.rmeta.as_ref())
164 .expect("No sources for crate").1;
165 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
172 fn verify_no_symbol_conflicts(&self,
175 // Check for (potential) conflicts with the local crate
176 if self.local_crate_name == root.name &&
177 self.sess.local_crate_disambiguator() == root.disambiguator {
178 span_fatal!(self.sess, span, E0519,
179 "the current crate is indistinguishable from one of its \
180 dependencies: it has the same crate-name `{}` and was \
181 compiled with the same `-C metadata` arguments. This \
182 will result in symbol conflicts between the two.",
186 // Check for conflicts with any crate loaded so far
187 self.cstore.iter_crate_data(|_, other| {
188 if other.root.name == root.name && // same crate-name
189 other.root.disambiguator == root.disambiguator && // same crate-disambiguator
190 other.root.hash != root.hash { // but different SVH
191 span_fatal!(self.sess, span, E0523,
192 "found two different crates with name `{}` that are \
193 not distinguished by differing `-C metadata`. This \
194 will result in symbol conflicts between the two.",
200 fn register_crate(&mut self,
201 root: &Option<CratePaths>,
206 -> (CrateNum, Lrc<cstore::CrateMetadata>) {
207 let crate_root = lib.metadata.get_root();
208 info!("register crate `extern crate {} as {}`", crate_root.name, ident);
209 self.verify_no_symbol_conflicts(span, &crate_root);
211 // Claim this crate number and cache it
212 let cnum = self.cstore.alloc_new_crate_num();
214 // Stash paths for top-most crate locally if necessary.
215 let crate_paths = if root.is_none() {
217 ident: ident.to_string(),
218 dylib: lib.dylib.clone().map(|p| p.0),
219 rlib: lib.rlib.clone().map(|p| p.0),
220 rmeta: lib.rmeta.clone().map(|p| p.0),
225 // Maintain a reference to the top most crate.
226 let root = if root.is_some() { root } else { &crate_paths };
228 let Library { dylib, rlib, rmeta, metadata } = lib;
229 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
231 let dependencies: Vec<CrateNum> = cnum_map.iter().cloned().collect();
233 let proc_macros = crate_root.proc_macro_decls_static.map(|_| {
234 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
237 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
238 if let Some(proc_macros) = &proc_macros {
239 proc_macro_def_path_table(&crate_root, proc_macros)
241 crate_root.def_path_table.decode((&metadata, self.sess))
245 let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
248 let trait_impls = crate_root
250 .decode((&metadata, self.sess))
251 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
254 let cmeta = cstore::CrateMetadata {
255 name: crate_root.name,
256 imported_name: ident,
257 extern_crate: Lock::new(None),
258 def_path_table: Lrc::new(def_path_table),
265 dependencies: Lock::new(dependencies),
266 source_map_import_info: RwLock::new(vec![]),
267 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
268 dep_kind: Lock::new(dep_kind),
269 source: cstore::CrateSource {
276 let cmeta = Lrc::new(cmeta);
277 self.cstore.set_crate_data(cnum, cmeta.clone());
281 fn resolve_crate<'b>(
283 root: &'b Option<CratePaths>,
286 hash: Option<&'b Svh>,
287 extra_filename: Option<&'b str>,
290 mut dep_kind: DepKind,
291 ) -> Result<(CrateNum, Lrc<cstore::CrateMetadata>), LoadError<'b>> {
292 info!("resolving crate `extern crate {} as {}`", name, ident);
293 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
294 LoadResult::Previous(cnum)
296 info!("falling back to a load");
297 let mut locate_ctxt = locator::Context {
302 hash: hash.map(|a| &*a),
303 extra_filename: extra_filename,
304 filesearch: self.sess.target_filesearch(path_kind),
305 target: &self.sess.target.target,
306 triple: &self.sess.opts.target_triple,
308 rejected_via_hash: vec![],
309 rejected_via_triple: vec![],
310 rejected_via_kind: vec![],
311 rejected_via_version: vec![],
312 rejected_via_filename: vec![],
313 should_match_name: true,
314 is_proc_macro: Some(false),
315 metadata_loader: &*self.cstore.metadata_loader,
318 self.load(&mut locate_ctxt).or_else(|| {
319 dep_kind = DepKind::UnexportedMacrosOnly;
321 let mut proc_macro_locator = locator::Context {
322 target: &self.sess.host,
323 triple: &TargetTriple::from_triple(config::host_triple()),
324 filesearch: self.sess.host_filesearch(path_kind),
325 rejected_via_hash: vec![],
326 rejected_via_triple: vec![],
327 rejected_via_kind: vec![],
328 rejected_via_version: vec![],
329 rejected_via_filename: vec![],
330 is_proc_macro: Some(true),
334 self.load(&mut proc_macro_locator)
335 }).ok_or_else(move || LoadError::LocatorError(locate_ctxt))?
339 LoadResult::Previous(cnum) => {
340 let data = self.cstore.get_crate_data(cnum);
341 if data.root.proc_macro_decls_static.is_some() {
342 dep_kind = DepKind::UnexportedMacrosOnly;
344 data.dep_kind.with_lock(|data_dep_kind| {
345 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
349 LoadResult::Loaded(library) => {
350 Ok(self.register_crate(root, ident, span, library, dep_kind))
355 fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
356 let library = locate_ctxt.maybe_load_library_crate()?;
358 // In the case that we're loading a crate, but not matching
359 // against a hash, we could load a crate which has the same hash
360 // as an already loaded crate. If this is the case prevent
361 // duplicates by just using the first crate.
363 // Note that we only do this for target triple crates, though, as we
364 // don't want to match a host crate against an equivalent target one
366 let root = library.metadata.get_root();
367 if locate_ctxt.triple == &self.sess.opts.target_triple {
368 let mut result = LoadResult::Loaded(library);
369 self.cstore.iter_crate_data(|cnum, data| {
370 if data.root.name == root.name && root.hash == data.root.hash {
371 assert!(locate_ctxt.hash.is_none());
372 info!("load success, going to previous cnum: {}", cnum);
373 result = LoadResult::Previous(cnum);
378 Some(LoadResult::Loaded(library))
382 fn update_extern_crate(&mut self,
384 mut extern_crate: ExternCrate,
385 visited: &mut FxHashSet<(CrateNum, bool)>)
387 if !visited.insert((cnum, extern_crate.direct)) { return }
389 let cmeta = self.cstore.get_crate_data(cnum);
390 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
393 // - something over nothing (tuple.0);
394 // - direct extern crate to indirect (tuple.1);
395 // - shorter paths to longer (tuple.2).
399 cmp::Reverse(extern_crate.path_len),
401 let old_rank = match *old_extern_crate {
402 None => (false, false, cmp::Reverse(usize::max_value())),
406 cmp::Reverse(c.path_len),
409 if old_rank >= new_rank {
410 return; // no change needed
413 *old_extern_crate = Some(extern_crate);
414 drop(old_extern_crate);
416 // Propagate the extern crate info to dependencies.
417 extern_crate.direct = false;
418 for &dep_cnum in cmeta.dependencies.borrow().iter() {
419 self.update_extern_crate(dep_cnum, extern_crate, visited);
423 // Go through the crate metadata and load any crates that it references
424 fn resolve_crate_deps(&mut self,
425 root: &Option<CratePaths>,
426 crate_root: &CrateRoot,
427 metadata: &MetadataBlob,
431 -> cstore::CrateNumMap {
432 debug!("resolving deps of external crate");
433 if crate_root.proc_macro_decls_static.is_some() {
434 return cstore::CrateNumMap::new();
437 // The map from crate numbers in the crate we're resolving to local crate numbers.
438 // We map 0 and all other holes in the map to our parent crate. The "additional"
439 // self-dependencies should be harmless.
440 ::std::iter::once(krate).chain(crate_root.crate_deps
443 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
445 if dep.kind == DepKind::UnexportedMacrosOnly {
448 let dep_kind = match dep_kind {
449 DepKind::MacrosOnly => DepKind::MacrosOnly,
452 let (local_cnum, ..) = self.resolve_crate(
453 root, dep.name, dep.name, Some(&dep.hash), Some(&dep.extra_filename), span,
454 PathKind::Dependency, dep_kind,
455 ).unwrap_or_else(|err| err.report());
460 fn read_extension_crate(&mut self, span: Span, orig_name: Symbol, rename: Symbol)
462 info!("read extension crate `extern crate {} as {}`", orig_name, rename);
463 let target_triple = &self.sess.opts.target_triple;
464 let host_triple = TargetTriple::from_triple(config::host_triple());
465 let is_cross = target_triple != &host_triple;
466 let mut target_only = false;
467 let mut locate_ctxt = locator::Context {
473 extra_filename: None,
474 filesearch: self.sess.host_filesearch(PathKind::Crate),
475 target: &self.sess.host,
476 triple: &host_triple,
478 rejected_via_hash: vec![],
479 rejected_via_triple: vec![],
480 rejected_via_kind: vec![],
481 rejected_via_version: vec![],
482 rejected_via_filename: vec![],
483 should_match_name: true,
485 metadata_loader: &*self.cstore.metadata_loader,
487 let library = self.load(&mut locate_ctxt).or_else(|| {
491 // Try loading from target crates. This will abort later if we
492 // try to load a plugin registrar function,
495 locate_ctxt.target = &self.sess.target.target;
496 locate_ctxt.triple = target_triple;
497 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
499 self.load(&mut locate_ctxt)
501 let library = match library {
503 None => locate_ctxt.report_errs(),
506 let (dylib, metadata) = match library {
507 LoadResult::Previous(cnum) => {
508 let data = self.cstore.get_crate_data(cnum);
509 (data.source.dylib.clone(), PMDSource::Registered(data))
511 LoadResult::Loaded(library) => {
512 let dylib = library.dylib.clone();
513 let metadata = PMDSource::Owned(library);
520 dylib: dylib.map(|p| p.0),
525 /// Load custom derive macros.
527 /// Note that this is intentionally similar to how we load plugins today,
528 /// but also intentionally separate. Plugins are likely always going to be
529 /// implemented as dynamic libraries, but we have a possible future where
530 /// custom derive (and other macro-1.1 style features) are implemented via
531 /// executables and custom IPC.
532 fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
533 -> Vec<(ast::Name, Lrc<SyntaxExtension>)> {
535 use dynamic_lib::DynamicLibrary;
536 use proc_macro::bridge::client::ProcMacro;
537 use syntax_ext::deriving::custom::ProcMacroDerive;
538 use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
540 let path = match dylib {
541 Some(dylib) => dylib,
542 None => span_bug!(span, "proc-macro crate not dylib"),
544 // Make sure the path contains a / or the linker will search for it.
545 let path = env::current_dir().unwrap().join(path);
546 let lib = match DynamicLibrary::open(Some(&path)) {
548 Err(err) => self.sess.span_fatal(span, &err),
551 let sym = self.sess.generate_proc_macro_decls_symbol(root.disambiguator);
553 let sym = match lib.symbol(&sym) {
555 Err(err) => self.sess.span_fatal(span, &err),
557 *(sym as *const &[ProcMacro])
560 let extensions = decls.iter().map(|&decl| {
562 ProcMacro::CustomDerive { trait_name, attributes, client } => {
563 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
564 (trait_name, SyntaxExtension::ProcMacroDerive(
565 Box::new(ProcMacroDerive {
567 attrs: attrs.clone(),
573 ProcMacro::Attr { name, client } => {
574 (name, SyntaxExtension::AttrProcMacro(
575 Box::new(AttrProcMacro { client }),
579 ProcMacro::Bang { name, client } => {
580 (name, SyntaxExtension::ProcMacro {
581 expander: Box::new(BangProcMacro { client }),
582 allow_internal_unstable: false,
583 edition: root.edition,
587 }).map(|(name, ext)| (Symbol::intern(name), Lrc::new(ext))).collect();
589 // Intentionally leak the dynamic library. We can't ever unload it
590 // since the library can make things that will live arbitrarily long.
596 /// Look for a plugin registrar. Returns library path, crate
597 /// SVH and DefIndex of the registrar function.
598 pub fn find_plugin_registrar(&mut self,
601 -> Option<(PathBuf, CrateDisambiguator)> {
602 let name = Symbol::intern(name);
603 let ekrate = self.read_extension_crate(span, name, name);
605 if ekrate.target_only {
606 // Need to abort before syntax expansion.
607 let message = format!("plugin `{}` is not available for triple `{}` \
610 config::host_triple(),
611 self.sess.opts.target_triple);
612 span_fatal!(self.sess, span, E0456, "{}", &message);
615 let root = ekrate.metadata.get_root();
616 match ekrate.dylib.as_ref() {
618 Some((dylib.to_path_buf(), root.disambiguator))
621 span_err!(self.sess, span, E0457,
622 "plugin `{}` only found in rlib format, but must be available \
625 // No need to abort because the loading code will just ignore this
632 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
633 // If we're only compiling an rlib, then there's no need to select a
634 // panic runtime, so we just skip this section entirely.
635 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
636 *ct != config::CrateType::Rlib
639 info!("panic runtime injection skipped, only generating rlib");
640 self.sess.injected_panic_runtime.set(None);
644 // If we need a panic runtime, we try to find an existing one here. At
645 // the same time we perform some general validation of the DAG we've got
646 // going such as ensuring everything has a compatible panic strategy.
648 // The logic for finding the panic runtime here is pretty much the same
649 // as the allocator case with the only addition that the panic strategy
650 // compilation mode also comes into play.
651 let desired_strategy = self.sess.panic_strategy();
652 let mut runtime_found = false;
653 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
654 "needs_panic_runtime");
656 self.cstore.iter_crate_data(|cnum, data| {
657 needs_panic_runtime = needs_panic_runtime ||
658 data.root.needs_panic_runtime;
659 if data.root.panic_runtime {
660 // Inject a dependency from all #![needs_panic_runtime] to this
661 // #![panic_runtime] crate.
662 self.inject_dependency_if(cnum, "a panic runtime",
663 &|data| data.root.needs_panic_runtime);
664 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
668 // If an explicitly linked and matching panic runtime was found, or if
669 // we just don't need one at all, then we're done here and there's
670 // nothing else to do.
671 if !needs_panic_runtime || runtime_found {
672 self.sess.injected_panic_runtime.set(None);
676 // By this point we know that we (a) need a panic runtime and (b) no
677 // panic runtime was explicitly linked. Here we just load an appropriate
678 // default runtime for our panic strategy and then inject the
681 // We may resolve to an already loaded crate (as the crate may not have
682 // been explicitly linked prior to this) and we may re-inject
683 // dependencies again, but both of those situations are fine.
685 // Also note that we have yet to perform validation of the crate graph
686 // in terms of everyone has a compatible panic runtime format, that's
687 // performed later as part of the `dependency_format` module.
688 let name = match desired_strategy {
689 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
690 PanicStrategy::Abort => Symbol::intern("panic_abort"),
692 info!("panic runtime not found -- loading {}", name);
694 let dep_kind = DepKind::Implicit;
696 self.resolve_crate(&None, name, name, None, None, DUMMY_SP, PathKind::Crate, dep_kind)
697 .unwrap_or_else(|err| err.report());
699 // Sanity check the loaded crate to ensure it is indeed a panic runtime
700 // and the panic strategy is indeed what we thought it was.
701 if !data.root.panic_runtime {
702 self.sess.err(&format!("the crate `{}` is not a panic runtime",
705 if data.root.panic_strategy != desired_strategy {
706 self.sess.err(&format!("the crate `{}` does not have the panic \
708 name, desired_strategy.desc()));
711 self.sess.injected_panic_runtime.set(Some(cnum));
712 self.inject_dependency_if(cnum, "a panic runtime",
713 &|data| data.root.needs_panic_runtime);
716 fn inject_sanitizer_runtime(&mut self) {
717 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
718 // Sanitizers can only be used on some tested platforms with
719 // executables linked to `std`
720 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
721 "x86_64-apple-darwin"];
722 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
723 "x86_64-apple-darwin"];
724 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
725 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
727 let supported_targets = match *sanitizer {
728 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
729 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
730 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
731 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
733 if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
734 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
736 supported_targets.join("` or `")
741 // firstyear 2017 - during testing I was unable to access an OSX machine
742 // to make this work on different crate types. As a result, today I have
743 // only been able to test and support linux as a target.
744 if self.sess.target.target.llvm_target == "x86_64-unknown-linux-gnu" {
745 if !self.sess.crate_types.borrow().iter().all(|ct| {
748 config::CrateType::Staticlib |
749 config::CrateType::Executable => true,
750 // This crate will be compiled with the required
751 // instrumentation pass
752 config::CrateType::Rlib |
753 config::CrateType::Dylib |
754 config::CrateType::Cdylib =>
757 self.sess.err(&format!("Only executables, staticlibs, \
758 cdylibs, dylibs and rlibs can be compiled with \
767 if !self.sess.crate_types.borrow().iter().all(|ct| {
770 config::CrateType::Executable => true,
771 // This crate will be compiled with the required
772 // instrumentation pass
773 config::CrateType::Rlib => false,
775 self.sess.err(&format!("Only executables and rlibs can be \
776 compiled with `-Z sanitizer`"));
785 let mut uses_std = false;
786 self.cstore.iter_crate_data(|_, data| {
787 if data.name == "std" {
793 let name = match *sanitizer {
794 Sanitizer::Address => "rustc_asan",
795 Sanitizer::Leak => "rustc_lsan",
796 Sanitizer::Memory => "rustc_msan",
797 Sanitizer::Thread => "rustc_tsan",
799 info!("loading sanitizer: {}", name);
801 let symbol = Symbol::intern(name);
802 let dep_kind = DepKind::Explicit;
804 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
805 PathKind::Crate, dep_kind)
806 .unwrap_or_else(|err| err.report());
808 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
809 if !data.root.sanitizer_runtime {
810 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
814 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
819 fn inject_profiler_runtime(&mut self) {
820 if self.sess.opts.debugging_opts.profile ||
821 self.sess.opts.debugging_opts.pgo_gen.is_some()
823 info!("loading profiler");
825 let symbol = Symbol::intern("profiler_builtins");
826 let dep_kind = DepKind::Implicit;
828 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
829 PathKind::Crate, dep_kind)
830 .unwrap_or_else(|err| err.report());
832 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
833 if !data.root.profiler_runtime {
834 self.sess.err(&format!("the crate `profiler_builtins` is not \
835 a profiler runtime"));
840 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
841 let has_global_allocator = has_global_allocator(krate);
842 self.sess.has_global_allocator.set(has_global_allocator);
844 // Check to see if we actually need an allocator. This desire comes
845 // about through the `#![needs_allocator]` attribute and is typically
846 // written down in liballoc.
847 let mut needs_allocator = attr::contains_name(&krate.attrs,
849 self.cstore.iter_crate_data(|_, data| {
850 needs_allocator = needs_allocator || data.root.needs_allocator;
852 if !needs_allocator {
853 self.sess.allocator_kind.set(None);
857 // At this point we've determined that we need an allocator. Let's see
858 // if our compilation session actually needs an allocator based on what
860 let all_rlib = self.sess.crate_types.borrow()
864 config::CrateType::Rlib => true,
869 self.sess.allocator_kind.set(None);
873 // Ok, we need an allocator. Not only that but we're actually going to
874 // create an artifact that needs one linked in. Let's go find the one
875 // that we're going to link in.
877 // First up we check for global allocators. Look at the crate graph here
878 // and see what's a global allocator, including if we ourselves are a
880 let mut global_allocator = if has_global_allocator {
885 self.cstore.iter_crate_data(|_, data| {
886 if !data.root.has_global_allocator {
889 match global_allocator {
890 Some(Some(other_crate)) => {
891 self.sess.err(&format!("the #[global_allocator] in {} \
892 conflicts with this global \
898 self.sess.err(&format!("the #[global_allocator] in this \
899 crate conflicts with global \
900 allocator in: {}", data.root.name));
902 None => global_allocator = Some(Some(data.root.name)),
905 if global_allocator.is_some() {
906 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
910 // Ok we haven't found a global allocator but we still need an
911 // allocator. At this point our allocator request is typically fulfilled
912 // by the standard library, denoted by the `#![default_lib_allocator]`
914 let mut has_default = attr::contains_name(&krate.attrs, "default_lib_allocator");
915 self.cstore.iter_crate_data(|_, data| {
916 if data.root.has_default_lib_allocator {
922 self.sess.err("no global memory allocator found but one is \
923 required; link to std or \
924 add #[global_allocator] to a static item \
925 that implements the GlobalAlloc trait.");
927 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
929 fn has_global_allocator(krate: &ast::Crate) -> bool {
931 let mut f = Finder(false);
932 visit::walk_crate(&mut f, krate);
935 impl<'ast> visit::Visitor<'ast> for Finder {
936 fn visit_item(&mut self, i: &'ast ast::Item) {
937 if attr::contains_name(&i.attrs, "global_allocator") {
940 visit::walk_item(self, i)
947 fn inject_dependency_if(&self,
950 needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
951 // don't perform this validation if the session has errors, as one of
952 // those errors may indicate a circular dependency which could cause
953 // this to stack overflow.
954 if self.sess.has_errors() {
958 // Before we inject any dependencies, make sure we don't inject a
959 // circular dependency by validating that this crate doesn't
960 // transitively depend on any crates satisfying `needs_dep`.
961 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
962 let data = self.cstore.get_crate_data(dep);
963 if needs_dep(&data) {
964 self.sess.err(&format!("the crate `{}` cannot depend \
965 on a crate that needs {}, but \
967 self.cstore.get_crate_data(krate).root.name,
973 // All crates satisfying `needs_dep` do not explicitly depend on the
974 // crate provided for this compile, but in order for this compilation to
975 // be successfully linked we need to inject a dependency (to order the
976 // crates on the command line correctly).
977 self.cstore.iter_crate_data(|cnum, data| {
978 if !needs_dep(data) {
982 info!("injecting a dep from {} to {}", cnum, krate);
983 data.dependencies.borrow_mut().push(krate);
988 impl<'a> CrateLoader<'a> {
989 pub fn postprocess(&mut self, krate: &ast::Crate) {
990 self.inject_sanitizer_runtime();
991 self.inject_profiler_runtime();
992 self.inject_allocator_crate(krate);
993 self.inject_panic_runtime(krate);
995 if log_enabled!(log::Level::Info) {
996 dump_crates(&self.cstore);
1000 pub fn process_extern_crate(
1001 &mut self, item: &ast::Item, definitions: &Definitions,
1004 ast::ItemKind::ExternCrate(orig_name) => {
1005 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
1006 item.ident, orig_name);
1007 let orig_name = match orig_name {
1008 Some(orig_name) => {
1009 ::validate_crate_name(Some(self.sess), &orig_name.as_str(),
1013 None => item.ident.name,
1015 let dep_kind = if attr::contains_name(&item.attrs, "no_link") {
1016 DepKind::UnexportedMacrosOnly
1021 let (cnum, ..) = self.resolve_crate(
1022 &None, item.ident.name, orig_name, None, None,
1023 item.span, PathKind::Crate, dep_kind,
1024 ).unwrap_or_else(|err| err.report());
1026 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1027 let path_len = definitions.def_path(def_id.index).data.len();
1028 self.update_extern_crate(
1031 src: ExternCrateSource::Extern(def_id),
1036 &mut FxHashSet::default(),
1038 self.cstore.add_extern_mod_stmt_cnum(item.id, cnum);
1045 pub fn process_path_extern(
1050 let cnum = self.resolve_crate(
1051 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1052 ).unwrap_or_else(|err| err.report()).0;
1054 self.update_extern_crate(
1057 src: ExternCrateSource::Path,
1059 // to have the least priority in `update_extern_crate`
1060 path_len: usize::max_value(),
1063 &mut FxHashSet::default(),
1069 pub fn maybe_process_path_extern(
1073 ) -> Option<CrateNum> {
1074 let cnum = self.resolve_crate(
1075 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1078 self.update_extern_crate(
1081 src: ExternCrateSource::Path,
1083 // to have the least priority in `update_extern_crate`
1084 path_len: usize::max_value(),
1087 &mut FxHashSet::default(),