1 //! Validates all used crates and extern libraries and loads their metadata
3 use crate::cstore::{self, CStore, CrateSource, MetadataBlob};
4 use crate::locator::{self, CratePaths};
5 use crate::decoder::proc_macro_def_path_table;
6 use crate::schema::CrateRoot;
7 use rustc_data_structures::sync::{Lrc, RwLock, Lock};
9 use rustc::hir::def_id::CrateNum;
10 use rustc_data_structures::svh::Svh;
11 use rustc::middle::cstore::DepKind;
12 use rustc::mir::interpret::AllocDecodingState;
13 use rustc::session::{Session, CrateDisambiguator};
14 use rustc::session::config::{Sanitizer, self};
15 use rustc_target::spec::{PanicStrategy, TargetTriple};
16 use rustc::session::search_paths::PathKind;
17 use rustc::middle::cstore::{ExternCrate, ExternCrateSource};
18 use rustc::util::common::record_time;
19 use rustc::util::nodemap::FxHashSet;
20 use rustc::hir::map::Definitions;
23 use std::path::PathBuf;
28 use syntax::ext::allocator::{global_allocator_spans, AllocatorKind};
29 use syntax::ext::base::{SyntaxExtension, SyntaxExtensionKind};
30 use syntax::symbol::{Symbol, sym};
31 use syntax::{span_err, span_fatal};
32 use syntax_pos::{Span, DUMMY_SP};
33 use log::{debug, info, log_enabled};
36 pub dylib: Option<(PathBuf, PathKind)>,
37 pub rlib: Option<(PathBuf, PathKind)>,
38 pub rmeta: Option<(PathBuf, PathKind)>,
39 pub metadata: MetadataBlob,
42 pub struct CrateLoader<'a> {
43 pub sess: &'a Session,
45 local_crate_name: Symbol,
48 fn dump_crates(cstore: &CStore) {
49 info!("resolved crates:");
50 cstore.iter_crate_data(|_, data| {
51 info!(" name: {}", data.root.name);
52 info!(" cnum: {}", data.cnum);
53 info!(" hash: {}", data.root.hash);
54 info!(" reqd: {:?}", *data.dep_kind.lock());
55 let CrateSource { dylib, rlib, rmeta } = data.source.clone();
56 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
57 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
58 rmeta.map(|rl| info!(" rmeta: {}", rl.0.display()));
62 // Extra info about a crate loaded for plugins or exported macros.
63 struct ExtensionCrate {
65 dylib: Option<PathBuf>,
70 Registered(Lrc<cstore::CrateMetadata>),
74 impl Deref for PMDSource {
75 type Target = MetadataBlob;
77 fn deref(&self) -> &MetadataBlob {
79 PMDSource::Registered(ref cmd) => &cmd.blob,
80 PMDSource::Owned(ref lib) => &lib.metadata
91 LocatorError(locator::Context<'a>),
94 impl<'a> LoadError<'a> {
95 fn report(self) -> ! {
97 LoadError::LocatorError(locate_ctxt) => locate_ctxt.report_errs(),
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(entry) = self.sess.opts.externs.get(&*name.as_str()) {
134 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
135 let found = entry.locations.iter().filter_map(|l| l.as_ref()).any(|l| {
136 let l = fs::canonicalize(l).ok();
137 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
138 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
146 // Alright, so we've gotten this far which means that `data` has the
147 // right name, we don't have a hash, and we don't have a --extern
148 // pointing for ourselves. We're still not quite yet done because we
149 // have to make sure that this crate was found in the crate lookup
150 // path (this is a top-level dependency) as we don't want to
151 // implicitly load anything inside the dependency lookup path.
152 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
153 .or(source.rmeta.as_ref())
154 .expect("No sources for crate").1;
155 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
162 fn verify_no_symbol_conflicts(&self,
164 root: &CrateRoot<'_>) {
165 // Check for (potential) conflicts with the local crate
166 if self.local_crate_name == root.name &&
167 self.sess.local_crate_disambiguator() == root.disambiguator {
168 span_fatal!(self.sess, span, E0519,
169 "the current crate is indistinguishable from one of its \
170 dependencies: it has the same crate-name `{}` and was \
171 compiled with the same `-C metadata` arguments. This \
172 will result in symbol conflicts between the two.",
176 // Check for conflicts with any crate loaded so far
177 self.cstore.iter_crate_data(|_, other| {
178 if other.root.name == root.name && // same crate-name
179 other.root.disambiguator == root.disambiguator && // same crate-disambiguator
180 other.root.hash != root.hash { // but different SVH
181 span_fatal!(self.sess, span, E0523,
182 "found two different crates with name `{}` that are \
183 not distinguished by differing `-C metadata`. This \
184 will result in symbol conflicts between the two.",
192 host_lib: Option<Library>,
193 root: &Option<CratePaths>,
199 ) -> (CrateNum, Lrc<cstore::CrateMetadata>) {
200 let crate_root = lib.metadata.get_root();
201 self.verify_no_symbol_conflicts(span, &crate_root);
203 let private_dep = self.sess.opts.externs.get(&name.as_str())
204 .map(|e| e.is_private_dep)
207 info!("register crate `extern crate {} as {}` (private_dep = {})",
208 crate_root.name, ident, private_dep);
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 if self.sess.opts.debugging_opts.dual_proc_macros {
235 let host_lib = host_lib.unwrap();
236 self.load_derive_macros(
237 &host_lib.metadata.get_root(),
238 host_lib.dylib.map(|p| p.0),
242 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
246 let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
247 if let Some(proc_macros) = &proc_macros {
248 proc_macro_def_path_table(&crate_root, proc_macros)
250 crate_root.def_path_table.decode((&metadata, self.sess))
254 let interpret_alloc_index: Vec<u32> = crate_root.interpret_alloc_index
257 let trait_impls = crate_root
259 .decode((&metadata, self.sess))
260 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
263 let cmeta = cstore::CrateMetadata {
264 name: crate_root.name,
265 imported_name: ident,
266 extern_crate: Lock::new(None),
267 def_path_table: Lrc::new(def_path_table),
274 dependencies: Lock::new(dependencies),
275 source_map_import_info: RwLock::new(vec![]),
276 alloc_decoding_state: AllocDecodingState::new(interpret_alloc_index),
277 dep_kind: Lock::new(dep_kind),
278 source: cstore::CrateSource {
286 let cmeta = Lrc::new(cmeta);
287 self.cstore.set_crate_data(cnum, cmeta.clone());
291 fn load_proc_macro<'b>(
293 locate_ctxt: &mut locator::Context<'b>,
295 ) -> Option<(LoadResult, Option<Library>)>
299 // Use a new locator Context so trying to load a proc macro doesn't affect the error
301 let mut proc_macro_locator = locate_ctxt.clone();
303 // Try to load a proc macro
304 proc_macro_locator.is_proc_macro = Some(true);
306 // Load the proc macro crate for the target
307 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
308 proc_macro_locator.reset();
309 let result = match self.load(&mut proc_macro_locator)? {
310 LoadResult::Previous(cnum) => return Some((LoadResult::Previous(cnum), None)),
311 LoadResult::Loaded(library) => Some(LoadResult::Loaded(library))
313 // Don't look for a matching hash when looking for the host crate.
314 // It won't be the same as the target crate hash
315 locate_ctxt.hash = None;
316 // Use the locate_ctxt when looking for the host proc macro crate, as that is required
317 // so we want it to affect the error message
318 (locate_ctxt, result)
320 (&mut proc_macro_locator, None)
323 // Load the proc macro crate for the host
326 locator.is_proc_macro = Some(true);
327 locator.target = &self.sess.host;
328 locator.triple = TargetTriple::from_triple(config::host_triple());
329 locator.filesearch = self.sess.host_filesearch(path_kind);
331 let host_result = self.load(locator)?;
333 Some(if self.sess.opts.debugging_opts.dual_proc_macros {
334 let host_result = match host_result {
335 LoadResult::Previous(..) => {
336 panic!("host and target proc macros must be loaded in lock-step")
338 LoadResult::Loaded(library) => library
340 (target_result.unwrap(), Some(host_result))
346 fn resolve_crate<'b>(
348 root: &'b Option<CratePaths>,
351 hash: Option<&'b Svh>,
352 extra_filename: Option<&'b str>,
355 mut dep_kind: DepKind,
356 ) -> Result<(CrateNum, Lrc<cstore::CrateMetadata>), LoadError<'b>> {
357 info!("resolving crate `extern crate {} as {}`", name, ident);
358 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
359 (LoadResult::Previous(cnum), None)
361 info!("falling back to a load");
362 let mut locate_ctxt = locator::Context {
369 filesearch: self.sess.target_filesearch(path_kind),
370 target: &self.sess.target.target,
371 triple: self.sess.opts.target_triple.clone(),
373 rejected_via_hash: vec![],
374 rejected_via_triple: vec![],
375 rejected_via_kind: vec![],
376 rejected_via_version: vec![],
377 rejected_via_filename: vec![],
378 should_match_name: true,
379 is_proc_macro: Some(false),
380 metadata_loader: &*self.cstore.metadata_loader,
383 self.load(&mut locate_ctxt).map(|r| (r, None)).or_else(|| {
384 dep_kind = DepKind::UnexportedMacrosOnly;
385 self.load_proc_macro(&mut locate_ctxt, path_kind)
386 }).ok_or_else(move || LoadError::LocatorError(locate_ctxt))?
390 (LoadResult::Previous(cnum), None) => {
391 let data = self.cstore.get_crate_data(cnum);
392 if data.root.proc_macro_decls_static.is_some() {
393 dep_kind = DepKind::UnexportedMacrosOnly;
395 data.dep_kind.with_lock(|data_dep_kind| {
396 *data_dep_kind = cmp::max(*data_dep_kind, dep_kind);
400 (LoadResult::Loaded(library), host_library) => {
401 Ok(self.register_crate(host_library, root, ident, span, library, dep_kind, name))
407 fn load(&mut self, locate_ctxt: &mut locator::Context<'_>) -> Option<LoadResult> {
408 let library = locate_ctxt.maybe_load_library_crate()?;
410 // In the case that we're loading a crate, but not matching
411 // against a hash, we could load a crate which has the same hash
412 // as an already loaded crate. If this is the case prevent
413 // duplicates by just using the first crate.
415 // Note that we only do this for target triple crates, though, as we
416 // don't want to match a host crate against an equivalent target one
418 let root = library.metadata.get_root();
419 if locate_ctxt.triple == self.sess.opts.target_triple {
420 let mut result = LoadResult::Loaded(library);
421 self.cstore.iter_crate_data(|cnum, data| {
422 if data.root.name == root.name && root.hash == data.root.hash {
423 assert!(locate_ctxt.hash.is_none());
424 info!("load success, going to previous cnum: {}", cnum);
425 result = LoadResult::Previous(cnum);
430 Some(LoadResult::Loaded(library))
434 fn update_extern_crate(&mut self,
436 mut extern_crate: ExternCrate,
437 visited: &mut FxHashSet<(CrateNum, bool)>)
439 if !visited.insert((cnum, extern_crate.direct)) { return }
441 let cmeta = self.cstore.get_crate_data(cnum);
442 let mut old_extern_crate = cmeta.extern_crate.borrow_mut();
445 // - something over nothing (tuple.0);
446 // - direct extern crate to indirect (tuple.1);
447 // - shorter paths to longer (tuple.2).
451 cmp::Reverse(extern_crate.path_len),
453 let old_rank = match *old_extern_crate {
454 None => (false, false, cmp::Reverse(usize::max_value())),
458 cmp::Reverse(c.path_len),
461 if old_rank >= new_rank {
462 return; // no change needed
465 *old_extern_crate = Some(extern_crate);
466 drop(old_extern_crate);
468 // Propagate the extern crate info to dependencies.
469 extern_crate.direct = false;
470 for &dep_cnum in cmeta.dependencies.borrow().iter() {
471 self.update_extern_crate(dep_cnum, extern_crate, visited);
475 // Go through the crate metadata and load any crates that it references
476 fn resolve_crate_deps(&mut self,
477 root: &Option<CratePaths>,
478 crate_root: &CrateRoot<'_>,
479 metadata: &MetadataBlob,
483 -> cstore::CrateNumMap {
484 debug!("resolving deps of external crate");
485 if crate_root.proc_macro_decls_static.is_some() {
486 return cstore::CrateNumMap::new();
489 // The map from crate numbers in the crate we're resolving to local crate numbers.
490 // We map 0 and all other holes in the map to our parent crate. The "additional"
491 // self-dependencies should be harmless.
492 std::iter::once(krate).chain(crate_root.crate_deps
495 info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
497 if dep.kind == DepKind::UnexportedMacrosOnly {
500 let dep_kind = match dep_kind {
501 DepKind::MacrosOnly => DepKind::MacrosOnly,
504 let (local_cnum, ..) = self.resolve_crate(
505 root, dep.name, dep.name, Some(&dep.hash), Some(&dep.extra_filename), span,
506 PathKind::Dependency, dep_kind,
507 ).unwrap_or_else(|err| err.report());
512 fn read_extension_crate(&mut self, span: Span, orig_name: Symbol, rename: Symbol)
514 info!("read extension crate `extern crate {} as {}`", orig_name, rename);
515 let target_triple = self.sess.opts.target_triple.clone();
516 let host_triple = TargetTriple::from_triple(config::host_triple());
517 let is_cross = target_triple != host_triple;
518 let mut target_only = false;
519 let mut locate_ctxt = locator::Context {
525 extra_filename: None,
526 filesearch: self.sess.host_filesearch(PathKind::Crate),
527 target: &self.sess.host,
530 rejected_via_hash: vec![],
531 rejected_via_triple: vec![],
532 rejected_via_kind: vec![],
533 rejected_via_version: vec![],
534 rejected_via_filename: vec![],
535 should_match_name: true,
537 metadata_loader: &*self.cstore.metadata_loader,
539 let library = self.load(&mut locate_ctxt).or_else(|| {
543 // Try loading from target crates. This will abort later if we
544 // try to load a plugin registrar function,
547 locate_ctxt.target = &self.sess.target.target;
548 locate_ctxt.triple = target_triple;
549 locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
551 self.load(&mut locate_ctxt)
553 let library = match library {
555 None => locate_ctxt.report_errs(),
558 let (dylib, metadata) = match library {
559 LoadResult::Previous(cnum) => {
560 let data = self.cstore.get_crate_data(cnum);
561 (data.source.dylib.clone(), PMDSource::Registered(data))
563 LoadResult::Loaded(library) => {
564 let dylib = library.dylib.clone();
565 let metadata = PMDSource::Owned(library);
572 dylib: dylib.map(|p| p.0),
577 /// Loads custom derive macros.
579 /// Note that this is intentionally similar to how we load plugins today,
580 /// but also intentionally separate. Plugins are likely always going to be
581 /// implemented as dynamic libraries, but we have a possible future where
582 /// custom derive (and other macro-1.1 style features) are implemented via
583 /// executables and custom IPC.
584 fn load_derive_macros(&mut self, root: &CrateRoot<'_>, dylib: Option<PathBuf>, span: Span)
585 -> Vec<(ast::Name, Lrc<SyntaxExtension>)> {
587 use crate::dynamic_lib::DynamicLibrary;
588 use proc_macro::bridge::client::ProcMacro;
589 use syntax::ext::proc_macro::{BangProcMacro, AttrProcMacro, ProcMacroDerive};
591 let path = match dylib {
592 Some(dylib) => dylib,
593 None => span_bug!(span, "proc-macro crate not dylib"),
595 // Make sure the path contains a / or the linker will search for it.
596 let path = env::current_dir().unwrap().join(path);
597 let lib = match DynamicLibrary::open(Some(&path)) {
599 Err(err) => self.sess.span_fatal(span, &err),
602 let sym = self.sess.generate_proc_macro_decls_symbol(root.disambiguator);
604 let sym = match lib.symbol(&sym) {
606 Err(err) => self.sess.span_fatal(span, &err),
608 *(sym as *const &[ProcMacro])
611 let extensions = decls.iter().map(|&decl| {
612 let (name, kind, helper_attrs) = match decl {
613 ProcMacro::CustomDerive { trait_name, attributes, client } => {
615 attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
618 SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive {
619 client, attrs: helper_attrs.clone()
624 ProcMacro::Attr { name, client } => (
625 name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new()
627 ProcMacro::Bang { name, client } => (
628 name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new()
632 (Symbol::intern(name), Lrc::new(SyntaxExtension {
634 ..SyntaxExtension::default(kind, root.edition)
638 // Intentionally leak the dynamic library. We can't ever unload it
639 // since the library can make things that will live arbitrarily long.
645 /// Look for a plugin registrar. Returns library path, crate
646 /// SVH and DefIndex of the registrar function.
647 pub fn find_plugin_registrar(&mut self,
650 -> Option<(PathBuf, CrateDisambiguator)> {
651 let ekrate = self.read_extension_crate(span, name, name);
653 if ekrate.target_only {
654 // Need to abort before syntax expansion.
655 let message = format!("plugin `{}` is not available for triple `{}` \
658 config::host_triple(),
659 self.sess.opts.target_triple);
660 span_fatal!(self.sess, span, E0456, "{}", &message);
663 let root = ekrate.metadata.get_root();
664 match ekrate.dylib.as_ref() {
666 Some((dylib.to_path_buf(), root.disambiguator))
669 span_err!(self.sess, span, E0457,
670 "plugin `{}` only found in rlib format, but must be available \
673 // No need to abort because the loading code will just ignore this
680 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
681 // If we're only compiling an rlib, then there's no need to select a
682 // panic runtime, so we just skip this section entirely.
683 let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
684 *ct != config::CrateType::Rlib
687 info!("panic runtime injection skipped, only generating rlib");
688 self.sess.injected_panic_runtime.set(None);
692 // If we need a panic runtime, we try to find an existing one here. At
693 // the same time we perform some general validation of the DAG we've got
694 // going such as ensuring everything has a compatible panic strategy.
696 // The logic for finding the panic runtime here is pretty much the same
697 // as the allocator case with the only addition that the panic strategy
698 // compilation mode also comes into play.
699 let desired_strategy = self.sess.panic_strategy();
700 let mut runtime_found = false;
701 let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
702 sym::needs_panic_runtime);
704 self.cstore.iter_crate_data(|cnum, data| {
705 needs_panic_runtime = needs_panic_runtime ||
706 data.root.needs_panic_runtime;
707 if data.root.panic_runtime {
708 // Inject a dependency from all #![needs_panic_runtime] to this
709 // #![panic_runtime] crate.
710 self.inject_dependency_if(cnum, "a panic runtime",
711 &|data| data.root.needs_panic_runtime);
712 runtime_found = runtime_found || *data.dep_kind.lock() == DepKind::Explicit;
716 // If an explicitly linked and matching panic runtime was found, or if
717 // we just don't need one at all, then we're done here and there's
718 // nothing else to do.
719 if !needs_panic_runtime || runtime_found {
720 self.sess.injected_panic_runtime.set(None);
724 // By this point we know that we (a) need a panic runtime and (b) no
725 // panic runtime was explicitly linked. Here we just load an appropriate
726 // default runtime for our panic strategy and then inject the
729 // We may resolve to an already loaded crate (as the crate may not have
730 // been explicitly linked prior to this) and we may re-inject
731 // dependencies again, but both of those situations are fine.
733 // Also note that we have yet to perform validation of the crate graph
734 // in terms of everyone has a compatible panic runtime format, that's
735 // performed later as part of the `dependency_format` module.
736 let name = match desired_strategy {
737 PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
738 PanicStrategy::Abort => Symbol::intern("panic_abort"),
740 info!("panic runtime not found -- loading {}", name);
742 let dep_kind = DepKind::Implicit;
744 self.resolve_crate(&None, name, name, None, None, DUMMY_SP, PathKind::Crate, dep_kind)
745 .unwrap_or_else(|err| err.report());
747 // Sanity check the loaded crate to ensure it is indeed a panic runtime
748 // and the panic strategy is indeed what we thought it was.
749 if !data.root.panic_runtime {
750 self.sess.err(&format!("the crate `{}` is not a panic runtime",
753 if data.root.panic_strategy != desired_strategy {
754 self.sess.err(&format!("the crate `{}` does not have the panic \
756 name, desired_strategy.desc()));
759 self.sess.injected_panic_runtime.set(Some(cnum));
760 self.inject_dependency_if(cnum, "a panic runtime",
761 &|data| data.root.needs_panic_runtime);
764 fn inject_sanitizer_runtime(&mut self) {
765 if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
766 // Sanitizers can only be used on some tested platforms with
767 // executables linked to `std`
768 const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
769 "x86_64-apple-darwin"];
770 const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
771 "x86_64-apple-darwin"];
772 const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
773 const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
775 let supported_targets = match *sanitizer {
776 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
777 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
778 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
779 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
781 if !supported_targets.contains(&&*self.sess.opts.target_triple.triple()) {
782 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
784 supported_targets.join("` or `")
789 // firstyear 2017 - during testing I was unable to access an OSX machine
790 // to make this work on different crate types. As a result, today I have
791 // only been able to test and support linux as a target.
792 if self.sess.opts.target_triple.triple() == "x86_64-unknown-linux-gnu" {
793 if !self.sess.crate_types.borrow().iter().all(|ct| {
796 config::CrateType::Staticlib |
797 config::CrateType::Executable => true,
798 // This crate will be compiled with the required
799 // instrumentation pass
800 config::CrateType::Rlib |
801 config::CrateType::Dylib |
802 config::CrateType::Cdylib =>
805 self.sess.err(&format!("Only executables, staticlibs, \
806 cdylibs, dylibs and rlibs can be compiled with \
815 if !self.sess.crate_types.borrow().iter().all(|ct| {
818 config::CrateType::Executable => true,
819 // This crate will be compiled with the required
820 // instrumentation pass
821 config::CrateType::Rlib => false,
823 self.sess.err(&format!("Only executables and rlibs can be \
824 compiled with `-Z sanitizer`"));
833 let mut uses_std = false;
834 self.cstore.iter_crate_data(|_, data| {
835 if data.name == sym::std {
841 let name = match *sanitizer {
842 Sanitizer::Address => "rustc_asan",
843 Sanitizer::Leak => "rustc_lsan",
844 Sanitizer::Memory => "rustc_msan",
845 Sanitizer::Thread => "rustc_tsan",
847 info!("loading sanitizer: {}", name);
849 let symbol = Symbol::intern(name);
850 let dep_kind = DepKind::Explicit;
852 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
853 PathKind::Crate, dep_kind)
854 .unwrap_or_else(|err| err.report());
856 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
857 if !data.root.sanitizer_runtime {
858 self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
862 self.sess.err("Must link std to be compiled with `-Z sanitizer`");
867 fn inject_profiler_runtime(&mut self) {
868 if self.sess.opts.debugging_opts.profile ||
869 self.sess.opts.cg.profile_generate.enabled()
871 info!("loading profiler");
873 let symbol = Symbol::intern("profiler_builtins");
874 let dep_kind = DepKind::Implicit;
876 self.resolve_crate(&None, symbol, symbol, None, None, DUMMY_SP,
877 PathKind::Crate, dep_kind)
878 .unwrap_or_else(|err| err.report());
880 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
881 if !data.root.profiler_runtime {
882 self.sess.err(&format!("the crate `profiler_builtins` is not \
883 a profiler runtime"));
888 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
889 let has_global_allocator = match &*global_allocator_spans(krate) {
890 [span1, span2, ..] => {
891 self.sess.struct_span_err(*span2, "cannot define multiple global allocators")
892 .span_note(*span1, "the previous global allocator is defined here").emit();
895 spans => !spans.is_empty()
897 self.sess.has_global_allocator.set(has_global_allocator);
899 // Check to see if we actually need an allocator. This desire comes
900 // about through the `#![needs_allocator]` attribute and is typically
901 // written down in liballoc.
902 let mut needs_allocator = attr::contains_name(&krate.attrs,
903 sym::needs_allocator);
904 self.cstore.iter_crate_data(|_, data| {
905 needs_allocator = needs_allocator || data.root.needs_allocator;
907 if !needs_allocator {
908 self.sess.allocator_kind.set(None);
912 // At this point we've determined that we need an allocator. Let's see
913 // if our compilation session actually needs an allocator based on what
915 let all_rlib = self.sess.crate_types.borrow()
919 config::CrateType::Rlib => true,
924 self.sess.allocator_kind.set(None);
928 // Ok, we need an allocator. Not only that but we're actually going to
929 // create an artifact that needs one linked in. Let's go find the one
930 // that we're going to link in.
932 // First up we check for global allocators. Look at the crate graph here
933 // and see what's a global allocator, including if we ourselves are a
935 let mut global_allocator = if has_global_allocator {
940 self.cstore.iter_crate_data(|_, data| {
941 if !data.root.has_global_allocator {
944 match global_allocator {
945 Some(Some(other_crate)) => {
946 self.sess.err(&format!("the `#[global_allocator]` in {} \
947 conflicts with this global \
953 self.sess.err(&format!("the `#[global_allocator]` in this \
954 crate conflicts with global \
955 allocator in: {}", data.root.name));
957 None => global_allocator = Some(Some(data.root.name)),
960 if global_allocator.is_some() {
961 self.sess.allocator_kind.set(Some(AllocatorKind::Global));
965 // Ok we haven't found a global allocator but we still need an
966 // allocator. At this point our allocator request is typically fulfilled
967 // by the standard library, denoted by the `#![default_lib_allocator]`
969 let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
970 self.cstore.iter_crate_data(|_, data| {
971 if data.root.has_default_lib_allocator {
977 self.sess.err("no global memory allocator found but one is \
978 required; link to std or \
979 add `#[global_allocator]` to a static item \
980 that implements the GlobalAlloc trait.");
982 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
985 fn inject_dependency_if(&self,
988 needs_dep: &dyn Fn(&cstore::CrateMetadata) -> bool) {
989 // don't perform this validation if the session has errors, as one of
990 // those errors may indicate a circular dependency which could cause
991 // this to stack overflow.
992 if self.sess.has_errors() {
996 // Before we inject any dependencies, make sure we don't inject a
997 // circular dependency by validating that this crate doesn't
998 // transitively depend on any crates satisfying `needs_dep`.
999 for dep in self.cstore.crate_dependencies_in_rpo(krate) {
1000 let data = self.cstore.get_crate_data(dep);
1001 if needs_dep(&data) {
1002 self.sess.err(&format!("the crate `{}` cannot depend \
1003 on a crate that needs {}, but \
1004 it depends on `{}`",
1005 self.cstore.get_crate_data(krate).root.name,
1011 // All crates satisfying `needs_dep` do not explicitly depend on the
1012 // crate provided for this compile, but in order for this compilation to
1013 // be successfully linked we need to inject a dependency (to order the
1014 // crates on the command line correctly).
1015 self.cstore.iter_crate_data(|cnum, data| {
1016 if !needs_dep(data) {
1020 info!("injecting a dep from {} to {}", cnum, krate);
1021 data.dependencies.borrow_mut().push(krate);
1026 impl<'a> CrateLoader<'a> {
1027 pub fn postprocess(&mut self, krate: &ast::Crate) {
1028 self.inject_sanitizer_runtime();
1029 self.inject_profiler_runtime();
1030 self.inject_allocator_crate(krate);
1031 self.inject_panic_runtime(krate);
1033 if log_enabled!(log::Level::Info) {
1034 dump_crates(&self.cstore);
1038 pub fn process_extern_crate(
1039 &mut self, item: &ast::Item, definitions: &Definitions,
1042 ast::ItemKind::ExternCrate(orig_name) => {
1043 debug!("resolving extern crate stmt. ident: {} orig_name: {:?}",
1044 item.ident, orig_name);
1045 let orig_name = match orig_name {
1046 Some(orig_name) => {
1047 crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
1051 None => item.ident.name,
1053 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
1054 DepKind::UnexportedMacrosOnly
1059 let (cnum, ..) = self.resolve_crate(
1060 &None, item.ident.name, orig_name, None, None,
1061 item.span, PathKind::Crate, dep_kind,
1062 ).unwrap_or_else(|err| err.report());
1064 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1065 let path_len = definitions.def_path(def_id.index).data.len();
1066 self.update_extern_crate(
1069 src: ExternCrateSource::Extern(def_id),
1074 &mut FxHashSet::default(),
1076 self.cstore.add_extern_mod_stmt_cnum(item.id, cnum);
1083 pub fn process_path_extern(
1088 let cnum = self.resolve_crate(
1089 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1090 ).unwrap_or_else(|err| err.report()).0;
1092 self.update_extern_crate(
1095 src: ExternCrateSource::Path,
1097 // to have the least priority in `update_extern_crate`
1098 path_len: usize::max_value(),
1101 &mut FxHashSet::default(),
1107 pub fn maybe_process_path_extern(
1111 ) -> Option<CrateNum> {
1112 let cnum = self.resolve_crate(
1113 &None, name, name, None, None, span, PathKind::Crate, DepKind::Explicit
1116 self.update_extern_crate(
1119 src: ExternCrateSource::Path,
1121 // to have the least priority in `update_extern_crate`
1122 path_len: usize::max_value(),
1125 &mut FxHashSet::default(),