]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/creader.rs
Use 128 bit instead of Symbol for crate disambiguator
[rust.git] / src / librustc_metadata / creader.rs
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.
4 //
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.
10
11 //! Validates all used crates and extern libraries and loads their metadata
12
13 use cstore::{self, CStore, CrateSource, MetadataBlob};
14 use locator::{self, CratePaths};
15 use native_libs::relevant_lib;
16 use schema::CrateRoot;
17
18 use rustc::ich::Fingerprint;
19 use rustc::hir::def_id::{CrateNum, DefIndex, CRATE_DEF_INDEX};
20 use rustc::hir::svh::Svh;
21 use rustc::middle::allocator::AllocatorKind;
22 use rustc::middle::cstore::DepKind;
23 use rustc::session::Session;
24 use rustc::session::config::{Sanitizer, self};
25 use rustc_back::PanicStrategy;
26 use rustc::session::search_paths::PathKind;
27 use rustc::middle;
28 use rustc::middle::cstore::{validate_crate_name, ExternCrate};
29 use rustc::util::common::record_time;
30 use rustc::util::nodemap::FxHashSet;
31 use rustc::hir::map::Definitions;
32
33 use std::cell::{RefCell, Cell};
34 use std::ops::Deref;
35 use std::path::PathBuf;
36 use std::rc::Rc;
37 use std::{cmp, fs};
38
39 use syntax::ast;
40 use syntax::attr;
41 use syntax::ext::base::SyntaxExtension;
42 use syntax::symbol::Symbol;
43 use syntax::visit;
44 use syntax_pos::{Span, DUMMY_SP};
45 use log;
46
47 pub struct Library {
48     pub dylib: Option<(PathBuf, PathKind)>,
49     pub rlib: Option<(PathBuf, PathKind)>,
50     pub rmeta: Option<(PathBuf, PathKind)>,
51     pub metadata: MetadataBlob,
52 }
53
54 pub struct CrateLoader<'a> {
55     pub sess: &'a Session,
56     cstore: &'a CStore,
57     next_crate_num: CrateNum,
58     local_crate_name: Symbol,
59 }
60
61 fn dump_crates(cstore: &CStore) {
62     info!("resolved crates:");
63     cstore.iter_crate_data(|_, data| {
64         info!("  name: {}", data.name());
65         info!("  cnum: {}", data.cnum);
66         info!("  hash: {}", data.hash());
67         info!("  reqd: {:?}", data.dep_kind.get());
68         let CrateSource { dylib, rlib, rmeta } = data.source.clone();
69         dylib.map(|dl| info!("  dylib: {}", dl.0.display()));
70         rlib.map(|rl|  info!("   rlib: {}", rl.0.display()));
71         rmeta.map(|rl| info!("   rmeta: {}", rl.0.display()));
72     });
73 }
74
75 #[derive(Debug)]
76 struct ExternCrateInfo {
77     ident: Symbol,
78     name: Symbol,
79     id: ast::NodeId,
80     dep_kind: DepKind,
81 }
82
83 // Extra info about a crate loaded for plugins or exported macros.
84 struct ExtensionCrate {
85     metadata: PMDSource,
86     dylib: Option<PathBuf>,
87     target_only: bool,
88 }
89
90 enum PMDSource {
91     Registered(Rc<cstore::CrateMetadata>),
92     Owned(Library),
93 }
94
95 impl Deref for PMDSource {
96     type Target = MetadataBlob;
97
98     fn deref(&self) -> &MetadataBlob {
99         match *self {
100             PMDSource::Registered(ref cmd) => &cmd.blob,
101             PMDSource::Owned(ref lib) => &lib.metadata
102         }
103     }
104 }
105
106 enum LoadResult {
107     Previous(CrateNum),
108     Loaded(Library),
109 }
110
111 impl<'a> CrateLoader<'a> {
112     pub fn new(sess: &'a Session, cstore: &'a CStore, local_crate_name: &str) -> Self {
113         CrateLoader {
114             sess,
115             cstore,
116             next_crate_num: cstore.next_crate_num(),
117             local_crate_name: Symbol::intern(local_crate_name),
118         }
119     }
120
121     fn extract_crate_info(&self, i: &ast::Item) -> Option<ExternCrateInfo> {
122         match i.node {
123             ast::ItemKind::ExternCrate(ref path_opt) => {
124                 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
125                        i.ident, path_opt);
126                 let name = match *path_opt {
127                     Some(name) => {
128                         validate_crate_name(Some(self.sess), &name.as_str(),
129                                             Some(i.span));
130                         name
131                     }
132                     None => i.ident.name,
133                 };
134                 Some(ExternCrateInfo {
135                     ident: i.ident.name,
136                     name,
137                     id: i.id,
138                     dep_kind: if attr::contains_name(&i.attrs, "no_link") {
139                         DepKind::UnexportedMacrosOnly
140                     } else {
141                         DepKind::Explicit
142                     },
143                 })
144             }
145             _ => None
146         }
147     }
148
149     fn existing_match(&self, name: Symbol, hash: Option<&Svh>, kind: PathKind)
150                       -> Option<CrateNum> {
151         let mut ret = None;
152         self.cstore.iter_crate_data(|cnum, data| {
153             if data.name != name { return }
154
155             match hash {
156                 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
157                 Some(..) => return,
158                 None => {}
159             }
160
161             // When the hash is None we're dealing with a top-level dependency
162             // in which case we may have a specification on the command line for
163             // this library. Even though an upstream library may have loaded
164             // something of the same name, we have to make sure it was loaded
165             // from the exact same location as well.
166             //
167             // We're also sure to compare *paths*, not actual byte slices. The
168             // `source` stores paths which are normalized which may be different
169             // from the strings on the command line.
170             let source = &self.cstore.get_crate_data(cnum).source;
171             if let Some(locs) = self.sess.opts.externs.get(&*name.as_str()) {
172                 let found = locs.iter().any(|l| {
173                     let l = fs::canonicalize(l).ok();
174                     source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
175                     source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
176                 });
177                 if found {
178                     ret = Some(cnum);
179                 }
180                 return
181             }
182
183             // Alright, so we've gotten this far which means that `data` has the
184             // right name, we don't have a hash, and we don't have a --extern
185             // pointing for ourselves. We're still not quite yet done because we
186             // have to make sure that this crate was found in the crate lookup
187             // path (this is a top-level dependency) as we don't want to
188             // implicitly load anything inside the dependency lookup path.
189             let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
190                                   .or(source.rmeta.as_ref())
191                                   .expect("No sources for crate").1;
192             if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
193                 ret = Some(cnum);
194             }
195         });
196         return ret;
197     }
198
199     fn verify_no_symbol_conflicts(&self,
200                                   span: Span,
201                                   root: &CrateRoot) {
202         // Check for (potential) conflicts with the local crate
203         if self.local_crate_name == root.name &&
204            self.sess.local_crate_disambiguator() == root.disambiguator {
205             span_fatal!(self.sess, span, E0519,
206                         "the current crate is indistinguishable from one of its \
207                          dependencies: it has the same crate-name `{}` and was \
208                          compiled with the same `-C metadata` arguments. This \
209                          will result in symbol conflicts between the two.",
210                         root.name)
211         }
212
213         // Check for conflicts with any crate loaded so far
214         self.cstore.iter_crate_data(|_, other| {
215             if other.name() == root.name && // same crate-name
216                other.disambiguator() == root.disambiguator &&  // same crate-disambiguator
217                other.hash() != root.hash { // but different SVH
218                 span_fatal!(self.sess, span, E0523,
219                         "found two different crates with name `{}` that are \
220                          not distinguished by differing `-C metadata`. This \
221                          will result in symbol conflicts between the two.",
222                         root.name)
223             }
224         });
225     }
226
227     fn register_crate(&mut self,
228                       root: &Option<CratePaths>,
229                       ident: Symbol,
230                       name: Symbol,
231                       span: Span,
232                       lib: Library,
233                       dep_kind: DepKind)
234                       -> (CrateNum, Rc<cstore::CrateMetadata>) {
235         info!("register crate `extern crate {} as {}`", name, ident);
236         let crate_root = lib.metadata.get_root();
237         self.verify_no_symbol_conflicts(span, &crate_root);
238
239         // Claim this crate number and cache it
240         let cnum = self.next_crate_num;
241         self.next_crate_num = CrateNum::from_u32(cnum.as_u32() + 1);
242
243         // Stash paths for top-most crate locally if necessary.
244         let crate_paths = if root.is_none() {
245             Some(CratePaths {
246                 ident: ident.to_string(),
247                 dylib: lib.dylib.clone().map(|p| p.0),
248                 rlib:  lib.rlib.clone().map(|p| p.0),
249                 rmeta: lib.rmeta.clone().map(|p| p.0),
250             })
251         } else {
252             None
253         };
254         // Maintain a reference to the top most crate.
255         let root = if root.is_some() { root } else { &crate_paths };
256
257         let Library { dylib, rlib, rmeta, metadata } = lib;
258
259         let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, span, dep_kind);
260
261         let def_path_table = record_time(&self.sess.perf_stats.decode_def_path_tables_time, || {
262             crate_root.def_path_table.decode(&metadata)
263         });
264
265         let exported_symbols = crate_root.exported_symbols.decode(&metadata).collect();
266
267         let trait_impls = crate_root
268             .impls
269             .decode(&metadata)
270             .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
271             .collect();
272
273         let mut cmeta = cstore::CrateMetadata {
274             name,
275             extern_crate: Cell::new(None),
276             def_path_table: Rc::new(def_path_table),
277             exported_symbols,
278             trait_impls,
279             proc_macros: crate_root.macro_derive_registrar.map(|_| {
280                 self.load_derive_macros(&crate_root, dylib.clone().map(|p| p.0), span)
281             }),
282             root: crate_root,
283             blob: metadata,
284             cnum_map: RefCell::new(cnum_map),
285             cnum,
286             codemap_import_info: RefCell::new(vec![]),
287             attribute_cache: RefCell::new([Vec::new(), Vec::new()]),
288             dep_kind: Cell::new(dep_kind),
289             source: cstore::CrateSource {
290                 dylib,
291                 rlib,
292                 rmeta,
293             },
294             // Initialize this with an empty set. The field is populated below
295             // after we were able to deserialize its contents.
296             dllimport_foreign_items: FxHashSet(),
297         };
298
299         let dllimports: FxHashSet<_> = cmeta
300             .root
301             .native_libraries
302             .decode(&cmeta)
303             .filter(|lib| relevant_lib(self.sess, lib) &&
304                           lib.kind == cstore::NativeLibraryKind::NativeUnknown)
305             .flat_map(|lib| {
306                 assert!(lib.foreign_items.iter().all(|def_id| def_id.krate == cnum));
307                 lib.foreign_items.into_iter().map(|def_id| def_id.index)
308             })
309             .collect();
310
311         cmeta.dllimport_foreign_items = dllimports;
312
313         let cmeta = Rc::new(cmeta);
314         self.cstore.set_crate_data(cnum, cmeta.clone());
315         (cnum, cmeta)
316     }
317
318     fn resolve_crate(&mut self,
319                      root: &Option<CratePaths>,
320                      ident: Symbol,
321                      name: Symbol,
322                      hash: Option<&Svh>,
323                      span: Span,
324                      path_kind: PathKind,
325                      mut dep_kind: DepKind)
326                      -> (CrateNum, Rc<cstore::CrateMetadata>) {
327         info!("resolving crate `extern crate {} as {}`", name, ident);
328         let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
329             LoadResult::Previous(cnum)
330         } else {
331             info!("falling back to a load");
332             let mut locate_ctxt = locator::Context {
333                 sess: self.sess,
334                 span,
335                 ident,
336                 crate_name: name,
337                 hash: hash.map(|a| &*a),
338                 filesearch: self.sess.target_filesearch(path_kind),
339                 target: &self.sess.target.target,
340                 triple: &self.sess.opts.target_triple,
341                 root,
342                 rejected_via_hash: vec![],
343                 rejected_via_triple: vec![],
344                 rejected_via_kind: vec![],
345                 rejected_via_version: vec![],
346                 rejected_via_filename: vec![],
347                 should_match_name: true,
348                 is_proc_macro: Some(false),
349                 metadata_loader: &*self.cstore.metadata_loader,
350             };
351
352             self.load(&mut locate_ctxt).or_else(|| {
353                 dep_kind = DepKind::UnexportedMacrosOnly;
354
355                 let mut proc_macro_locator = locator::Context {
356                     target: &self.sess.host,
357                     triple: config::host_triple(),
358                     filesearch: self.sess.host_filesearch(path_kind),
359                     rejected_via_hash: vec![],
360                     rejected_via_triple: vec![],
361                     rejected_via_kind: vec![],
362                     rejected_via_version: vec![],
363                     rejected_via_filename: vec![],
364                     is_proc_macro: Some(true),
365                     ..locate_ctxt
366                 };
367
368                 self.load(&mut proc_macro_locator)
369             }).unwrap_or_else(|| locate_ctxt.report_errs())
370         };
371
372         match result {
373             LoadResult::Previous(cnum) => {
374                 let data = self.cstore.get_crate_data(cnum);
375                 if data.root.macro_derive_registrar.is_some() {
376                     dep_kind = DepKind::UnexportedMacrosOnly;
377                 }
378                 data.dep_kind.set(cmp::max(data.dep_kind.get(), dep_kind));
379                 (cnum, data)
380             }
381             LoadResult::Loaded(library) => {
382                 self.register_crate(root, ident, name, span, library, dep_kind)
383             }
384         }
385     }
386
387     fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
388         let library = match locate_ctxt.maybe_load_library_crate() {
389             Some(lib) => lib,
390             None => return None,
391         };
392
393         // In the case that we're loading a crate, but not matching
394         // against a hash, we could load a crate which has the same hash
395         // as an already loaded crate. If this is the case prevent
396         // duplicates by just using the first crate.
397         //
398         // Note that we only do this for target triple crates, though, as we
399         // don't want to match a host crate against an equivalent target one
400         // already loaded.
401         let root = library.metadata.get_root();
402         if locate_ctxt.triple == self.sess.opts.target_triple {
403             let mut result = LoadResult::Loaded(library);
404             self.cstore.iter_crate_data(|cnum, data| {
405                 if data.name() == root.name && root.hash == data.hash() {
406                     assert!(locate_ctxt.hash.is_none());
407                     info!("load success, going to previous cnum: {}", cnum);
408                     result = LoadResult::Previous(cnum);
409                 }
410             });
411             Some(result)
412         } else {
413             Some(LoadResult::Loaded(library))
414         }
415     }
416
417     fn update_extern_crate(&mut self,
418                            cnum: CrateNum,
419                            mut extern_crate: ExternCrate,
420                            visited: &mut FxHashSet<(CrateNum, bool)>)
421     {
422         if !visited.insert((cnum, extern_crate.direct)) { return }
423
424         let cmeta = self.cstore.get_crate_data(cnum);
425         let old_extern_crate = cmeta.extern_crate.get();
426
427         // Prefer:
428         // - something over nothing (tuple.0);
429         // - direct extern crate to indirect (tuple.1);
430         // - shorter paths to longer (tuple.2).
431         let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
432         let old_rank = match old_extern_crate {
433             None => (false, false, !0),
434             Some(ref c) => (true, c.direct, !c.path_len),
435         };
436
437         if old_rank >= new_rank {
438             return; // no change needed
439         }
440
441         cmeta.extern_crate.set(Some(extern_crate));
442         // Propagate the extern crate info to dependencies.
443         extern_crate.direct = false;
444         for &dep_cnum in cmeta.cnum_map.borrow().iter() {
445             self.update_extern_crate(dep_cnum, extern_crate, visited);
446         }
447     }
448
449     // Go through the crate metadata and load any crates that it references
450     fn resolve_crate_deps(&mut self,
451                           root: &Option<CratePaths>,
452                           crate_root: &CrateRoot,
453                           metadata: &MetadataBlob,
454                           krate: CrateNum,
455                           span: Span,
456                           dep_kind: DepKind)
457                           -> cstore::CrateNumMap {
458         debug!("resolving deps of external crate");
459         if crate_root.macro_derive_registrar.is_some() {
460             return cstore::CrateNumMap::new();
461         }
462
463         // The map from crate numbers in the crate we're resolving to local crate numbers.
464         // We map 0 and all other holes in the map to our parent crate. The "additional"
465         // self-dependencies should be harmless.
466         ::std::iter::once(krate).chain(crate_root.crate_deps
467                                                  .decode(metadata)
468                                                  .map(|dep| {
469             debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
470             if dep.kind == DepKind::UnexportedMacrosOnly {
471                 return krate;
472             }
473             let dep_kind = match dep_kind {
474                 DepKind::MacrosOnly => DepKind::MacrosOnly,
475                 _ => dep.kind,
476             };
477             let (local_cnum, ..) = self.resolve_crate(
478                 root, dep.name, dep.name, Some(&dep.hash), span, PathKind::Dependency, dep_kind,
479             );
480             local_cnum
481         })).collect()
482     }
483
484     fn read_extension_crate(&mut self, span: Span, info: &ExternCrateInfo) -> ExtensionCrate {
485         info!("read extension crate {} `extern crate {} as {}` dep_kind={:?}",
486               info.id, info.name, info.ident, info.dep_kind);
487         let target_triple = &self.sess.opts.target_triple[..];
488         let is_cross = target_triple != config::host_triple();
489         let mut target_only = false;
490         let mut locate_ctxt = locator::Context {
491             sess: self.sess,
492             span,
493             ident: info.ident,
494             crate_name: info.name,
495             hash: None,
496             filesearch: self.sess.host_filesearch(PathKind::Crate),
497             target: &self.sess.host,
498             triple: config::host_triple(),
499             root: &None,
500             rejected_via_hash: vec![],
501             rejected_via_triple: vec![],
502             rejected_via_kind: vec![],
503             rejected_via_version: vec![],
504             rejected_via_filename: vec![],
505             should_match_name: true,
506             is_proc_macro: None,
507             metadata_loader: &*self.cstore.metadata_loader,
508         };
509         let library = self.load(&mut locate_ctxt).or_else(|| {
510             if !is_cross {
511                 return None
512             }
513             // Try loading from target crates. This will abort later if we
514             // try to load a plugin registrar function,
515             target_only = true;
516
517             locate_ctxt.target = &self.sess.target.target;
518             locate_ctxt.triple = target_triple;
519             locate_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
520
521             self.load(&mut locate_ctxt)
522         });
523         let library = match library {
524             Some(l) => l,
525             None => locate_ctxt.report_errs(),
526         };
527
528         let (dylib, metadata) = match library {
529             LoadResult::Previous(cnum) => {
530                 let data = self.cstore.get_crate_data(cnum);
531                 (data.source.dylib.clone(), PMDSource::Registered(data))
532             }
533             LoadResult::Loaded(library) => {
534                 let dylib = library.dylib.clone();
535                 let metadata = PMDSource::Owned(library);
536                 (dylib, metadata)
537             }
538         };
539
540         ExtensionCrate {
541             metadata,
542             dylib: dylib.map(|p| p.0),
543             target_only,
544         }
545     }
546
547     /// Load custom derive macros.
548     ///
549     /// Note that this is intentionally similar to how we load plugins today,
550     /// but also intentionally separate. Plugins are likely always going to be
551     /// implemented as dynamic libraries, but we have a possible future where
552     /// custom derive (and other macro-1.1 style features) are implemented via
553     /// executables and custom IPC.
554     fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
555                           -> Vec<(ast::Name, Rc<SyntaxExtension>)> {
556         use std::{env, mem};
557         use proc_macro::TokenStream;
558         use proc_macro::__internal::Registry;
559         use rustc_back::dynamic_lib::DynamicLibrary;
560         use syntax_ext::deriving::custom::ProcMacroDerive;
561         use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
562
563         let path = match dylib {
564             Some(dylib) => dylib,
565             None => span_bug!(span, "proc-macro crate not dylib"),
566         };
567         // Make sure the path contains a / or the linker will search for it.
568         let path = env::current_dir().unwrap().join(path);
569         let lib = match DynamicLibrary::open(Some(&path)) {
570             Ok(lib) => lib,
571             Err(err) => self.sess.span_fatal(span, &err),
572         };
573
574         let sym = self.sess.generate_derive_registrar_symbol(root.disambiguator,
575                                                              root.macro_derive_registrar.unwrap());
576         let registrar = unsafe {
577             let sym = match lib.symbol(&sym) {
578                 Ok(f) => f,
579                 Err(err) => self.sess.span_fatal(span, &err),
580             };
581             mem::transmute::<*mut u8, fn(&mut Registry)>(sym)
582         };
583
584         struct MyRegistrar(Vec<(ast::Name, Rc<SyntaxExtension>)>);
585
586         impl Registry for MyRegistrar {
587             fn register_custom_derive(&mut self,
588                                       trait_name: &str,
589                                       expand: fn(TokenStream) -> TokenStream,
590                                       attributes: &[&'static str]) {
591                 let attrs = attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
592                 let derive = ProcMacroDerive::new(expand, attrs.clone());
593                 let derive = SyntaxExtension::ProcMacroDerive(Box::new(derive), attrs);
594                 self.0.push((Symbol::intern(trait_name), Rc::new(derive)));
595             }
596
597             fn register_attr_proc_macro(&mut self,
598                                         name: &str,
599                                         expand: fn(TokenStream, TokenStream) -> TokenStream) {
600                 let expand = SyntaxExtension::AttrProcMacro(
601                     Box::new(AttrProcMacro { inner: expand })
602                 );
603                 self.0.push((Symbol::intern(name), Rc::new(expand)));
604             }
605
606             fn register_bang_proc_macro(&mut self,
607                                         name: &str,
608                                         expand: fn(TokenStream) -> TokenStream) {
609                 let expand = SyntaxExtension::ProcMacro(
610                     Box::new(BangProcMacro { inner: expand })
611                 );
612                 self.0.push((Symbol::intern(name), Rc::new(expand)));
613             }
614         }
615
616         let mut my_registrar = MyRegistrar(Vec::new());
617         registrar(&mut my_registrar);
618
619         // Intentionally leak the dynamic library. We can't ever unload it
620         // since the library can make things that will live arbitrarily long.
621         mem::forget(lib);
622         my_registrar.0
623     }
624
625     /// Look for a plugin registrar. Returns library path, crate
626     /// SVH and DefIndex of the registrar function.
627     pub fn find_plugin_registrar(&mut self,
628                                  span: Span,
629                                  name: &str)
630                                  -> Option<(PathBuf, Fingerprint, DefIndex)> {
631         let ekrate = self.read_extension_crate(span, &ExternCrateInfo {
632              name: Symbol::intern(name),
633              ident: Symbol::intern(name),
634              id: ast::DUMMY_NODE_ID,
635              dep_kind: DepKind::UnexportedMacrosOnly,
636         });
637
638         if ekrate.target_only {
639             // Need to abort before syntax expansion.
640             let message = format!("plugin `{}` is not available for triple `{}` \
641                                    (only found {})",
642                                   name,
643                                   config::host_triple(),
644                                   self.sess.opts.target_triple);
645             span_fatal!(self.sess, span, E0456, "{}", &message);
646         }
647
648         let root = ekrate.metadata.get_root();
649         match (ekrate.dylib.as_ref(), root.plugin_registrar_fn) {
650             (Some(dylib), Some(reg)) => {
651                 Some((dylib.to_path_buf(), root.disambiguator, reg))
652             }
653             (None, Some(_)) => {
654                 span_err!(self.sess, span, E0457,
655                           "plugin `{}` only found in rlib format, but must be available \
656                            in dylib format",
657                           name);
658                 // No need to abort because the loading code will just ignore this
659                 // empty dylib.
660                 None
661             }
662             _ => None,
663         }
664     }
665
666     fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
667         // If we're only compiling an rlib, then there's no need to select a
668         // panic runtime, so we just skip this section entirely.
669         let any_non_rlib = self.sess.crate_types.borrow().iter().any(|ct| {
670             *ct != config::CrateTypeRlib
671         });
672         if !any_non_rlib {
673             info!("panic runtime injection skipped, only generating rlib");
674             return
675         }
676
677         // If we need a panic runtime, we try to find an existing one here. At
678         // the same time we perform some general validation of the DAG we've got
679         // going such as ensuring everything has a compatible panic strategy.
680         //
681         // The logic for finding the panic runtime here is pretty much the same
682         // as the allocator case with the only addition that the panic strategy
683         // compilation mode also comes into play.
684         let desired_strategy = self.sess.panic_strategy();
685         let mut runtime_found = false;
686         let mut needs_panic_runtime = attr::contains_name(&krate.attrs,
687                                                           "needs_panic_runtime");
688
689         self.cstore.iter_crate_data(|cnum, data| {
690             needs_panic_runtime = needs_panic_runtime ||
691                                   data.needs_panic_runtime();
692             if data.is_panic_runtime() {
693                 // Inject a dependency from all #![needs_panic_runtime] to this
694                 // #![panic_runtime] crate.
695                 self.inject_dependency_if(cnum, "a panic runtime",
696                                           &|data| data.needs_panic_runtime());
697                 runtime_found = runtime_found || data.dep_kind.get() == DepKind::Explicit;
698             }
699         });
700
701         // If an explicitly linked and matching panic runtime was found, or if
702         // we just don't need one at all, then we're done here and there's
703         // nothing else to do.
704         if !needs_panic_runtime || runtime_found {
705             return
706         }
707
708         // By this point we know that we (a) need a panic runtime and (b) no
709         // panic runtime was explicitly linked. Here we just load an appropriate
710         // default runtime for our panic strategy and then inject the
711         // dependencies.
712         //
713         // We may resolve to an already loaded crate (as the crate may not have
714         // been explicitly linked prior to this) and we may re-inject
715         // dependencies again, but both of those situations are fine.
716         //
717         // Also note that we have yet to perform validation of the crate graph
718         // in terms of everyone has a compatible panic runtime format, that's
719         // performed later as part of the `dependency_format` module.
720         let name = match desired_strategy {
721             PanicStrategy::Unwind => Symbol::intern("panic_unwind"),
722             PanicStrategy::Abort => Symbol::intern("panic_abort"),
723         };
724         info!("panic runtime not found -- loading {}", name);
725
726         let dep_kind = DepKind::Implicit;
727         let (cnum, data) =
728             self.resolve_crate(&None, name, name, None, DUMMY_SP, PathKind::Crate, dep_kind);
729
730         // Sanity check the loaded crate to ensure it is indeed a panic runtime
731         // and the panic strategy is indeed what we thought it was.
732         if !data.is_panic_runtime() {
733             self.sess.err(&format!("the crate `{}` is not a panic runtime",
734                                    name));
735         }
736         if data.panic_strategy() != desired_strategy {
737             self.sess.err(&format!("the crate `{}` does not have the panic \
738                                     strategy `{}`",
739                                    name, desired_strategy.desc()));
740         }
741
742         self.sess.injected_panic_runtime.set(Some(cnum));
743         self.inject_dependency_if(cnum, "a panic runtime",
744                                   &|data| data.needs_panic_runtime());
745     }
746
747     fn inject_sanitizer_runtime(&mut self) {
748         if let Some(ref sanitizer) = self.sess.opts.debugging_opts.sanitizer {
749             // Sanitizers can only be used on some tested platforms with
750             // executables linked to `std`
751             const ASAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
752                                                       "x86_64-apple-darwin"];
753             const TSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu",
754                                                       "x86_64-apple-darwin"];
755             const LSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
756             const MSAN_SUPPORTED_TARGETS: &[&str] = &["x86_64-unknown-linux-gnu"];
757
758             let supported_targets = match *sanitizer {
759                 Sanitizer::Address => ASAN_SUPPORTED_TARGETS,
760                 Sanitizer::Thread => TSAN_SUPPORTED_TARGETS,
761                 Sanitizer::Leak => LSAN_SUPPORTED_TARGETS,
762                 Sanitizer::Memory => MSAN_SUPPORTED_TARGETS,
763             };
764             if !supported_targets.contains(&&*self.sess.target.target.llvm_target) {
765                 self.sess.err(&format!("{:?}Sanitizer only works with the `{}` target",
766                     sanitizer,
767                     supported_targets.join("` or `")
768                 ));
769                 return
770             }
771
772             // firstyear 2017 - during testing I was unable to access an OSX machine
773             // to make this work on different crate types. As a result, today I have
774             // only been able to test and support linux as a target.
775             if self.sess.target.target.llvm_target == "x86_64-unknown-linux-gnu" {
776                 if !self.sess.crate_types.borrow().iter().all(|ct| {
777                     match *ct {
778                         // Link the runtime
779                         config::CrateTypeStaticlib |
780                         config::CrateTypeExecutable => true,
781                         // This crate will be compiled with the required
782                         // instrumentation pass
783                         config::CrateTypeRlib |
784                         config::CrateTypeDylib |
785                         config::CrateTypeCdylib =>
786                             false,
787                         _ => {
788                             self.sess.err(&format!("Only executables, staticlibs, \
789                                 cdylibs, dylibs and rlibs can be compiled with \
790                                 `-Z sanitizer`"));
791                             false
792                         }
793                     }
794                 }) {
795                     return
796                 }
797             } else {
798                 if !self.sess.crate_types.borrow().iter().all(|ct| {
799                     match *ct {
800                         // Link the runtime
801                         config::CrateTypeExecutable => true,
802                         // This crate will be compiled with the required
803                         // instrumentation pass
804                         config::CrateTypeRlib => false,
805                         _ => {
806                             self.sess.err(&format!("Only executables and rlibs can be \
807                                                     compiled with `-Z sanitizer`"));
808                             false
809                         }
810                     }
811                 }) {
812                     return
813                 }
814             }
815
816             let mut uses_std = false;
817             self.cstore.iter_crate_data(|_, data| {
818                 if data.name == "std" {
819                     uses_std = true;
820                 }
821             });
822
823             if uses_std {
824                 let name = match *sanitizer {
825                     Sanitizer::Address => "rustc_asan",
826                     Sanitizer::Leak => "rustc_lsan",
827                     Sanitizer::Memory => "rustc_msan",
828                     Sanitizer::Thread => "rustc_tsan",
829                 };
830                 info!("loading sanitizer: {}", name);
831
832                 let symbol = Symbol::intern(name);
833                 let dep_kind = DepKind::Explicit;
834                 let (_, data) =
835                     self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
836                                        PathKind::Crate, dep_kind);
837
838                 // Sanity check the loaded crate to ensure it is indeed a sanitizer runtime
839                 if !data.is_sanitizer_runtime() {
840                     self.sess.err(&format!("the crate `{}` is not a sanitizer runtime",
841                                            name));
842                 }
843             } else {
844                 self.sess.err(&format!("Must link std to be compiled with `-Z sanitizer`"));
845             }
846         }
847     }
848
849     fn inject_profiler_runtime(&mut self) {
850         if self.sess.opts.debugging_opts.profile {
851             info!("loading profiler");
852
853             let symbol = Symbol::intern("profiler_builtins");
854             let dep_kind = DepKind::Implicit;
855             let (_, data) =
856                 self.resolve_crate(&None, symbol, symbol, None, DUMMY_SP,
857                                    PathKind::Crate, dep_kind);
858
859             // Sanity check the loaded crate to ensure it is indeed a profiler runtime
860             if !data.is_profiler_runtime() {
861                 self.sess.err(&format!("the crate `profiler_builtins` is not \
862                                         a profiler runtime"));
863             }
864         }
865     }
866
867     fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
868         let has_global_allocator = has_global_allocator(krate);
869         if has_global_allocator {
870             self.sess.has_global_allocator.set(true);
871         }
872
873         // Check to see if we actually need an allocator. This desire comes
874         // about through the `#![needs_allocator]` attribute and is typically
875         // written down in liballoc.
876         let mut needs_allocator = attr::contains_name(&krate.attrs,
877                                                       "needs_allocator");
878         self.cstore.iter_crate_data(|_, data| {
879             needs_allocator = needs_allocator || data.needs_allocator();
880         });
881         if !needs_allocator {
882             return
883         }
884
885         // At this point we've determined that we need an allocator. Let's see
886         // if our compilation session actually needs an allocator based on what
887         // we're emitting.
888         let mut need_lib_alloc = false;
889         let mut need_exe_alloc = false;
890         for ct in self.sess.crate_types.borrow().iter() {
891             match *ct {
892                 config::CrateTypeExecutable => need_exe_alloc = true,
893                 config::CrateTypeDylib |
894                 config::CrateTypeProcMacro |
895                 config::CrateTypeCdylib |
896                 config::CrateTypeStaticlib => need_lib_alloc = true,
897                 config::CrateTypeRlib => {}
898             }
899         }
900         if !need_lib_alloc && !need_exe_alloc {
901             return
902         }
903
904         // Ok, we need an allocator. Not only that but we're actually going to
905         // create an artifact that needs one linked in. Let's go find the one
906         // that we're going to link in.
907         //
908         // First up we check for global allocators. Look at the crate graph here
909         // and see what's a global allocator, including if we ourselves are a
910         // global allocator.
911         let mut global_allocator = if has_global_allocator {
912             Some(None)
913         } else {
914             None
915         };
916         self.cstore.iter_crate_data(|_, data| {
917             if !data.has_global_allocator() {
918                 return
919             }
920             match global_allocator {
921                 Some(Some(other_crate)) => {
922                     self.sess.err(&format!("the #[global_allocator] in {} \
923                                             conflicts with this global \
924                                             allocator in: {}",
925                                            other_crate,
926                                            data.name()));
927                 }
928                 Some(None) => {
929                     self.sess.err(&format!("the #[global_allocator] in this \
930                                             crate conflicts with global \
931                                             allocator in: {}", data.name()));
932                 }
933                 None => global_allocator = Some(Some(data.name())),
934             }
935         });
936         if global_allocator.is_some() {
937             self.sess.allocator_kind.set(Some(AllocatorKind::Global));
938             return
939         }
940
941         // Ok we haven't found a global allocator but we still need an
942         // allocator. At this point we'll either fall back to the "library
943         // allocator" or the "exe allocator" depending on a few variables. Let's
944         // figure out which one.
945         //
946         // Note that here we favor linking to the "library allocator" as much as
947         // possible. If we're not creating rustc's version of libstd
948         // (need_lib_alloc and prefer_dynamic) then we select `None`, and if the
949         // exe allocation crate doesn't exist for this target then we also
950         // select `None`.
951         let exe_allocation_crate_data =
952             if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
953                 None
954             } else {
955                 self.sess
956                     .target
957                     .target
958                     .options
959                     .exe_allocation_crate
960                     .as_ref()
961                     .map(|name| {
962                         // We've determined that we're injecting an "exe allocator" which means
963                         // that we're going to load up a whole new crate. An example of this is
964                         // that we're producing a normal binary on Linux which means we need to
965                         // load the `alloc_jemalloc` crate to link as an allocator.
966                         let name = Symbol::intern(name);
967                         let (cnum, data) = self.resolve_crate(&None,
968                                                               name,
969                                                               name,
970                                                               None,
971                                                               DUMMY_SP,
972                                                               PathKind::Crate,
973                                                               DepKind::Implicit);
974                         self.sess.injected_allocator.set(Some(cnum));
975                         data
976                     })
977             };
978
979         let allocation_crate_data = exe_allocation_crate_data.or_else(|| {
980             if attr::contains_name(&krate.attrs, "default_lib_allocator") {
981                 // Prefer self as the allocator if there's a collision
982                 return None;
983             }
984             // We're not actually going to inject an allocator, we're going to
985             // require that something in our crate graph is the default lib
986             // allocator. This is typically libstd, so this'll rarely be an
987             // error.
988             let mut allocator = None;
989             self.cstore.iter_crate_data(|_, data| {
990                 if allocator.is_none() && data.has_default_lib_allocator() {
991                     allocator = Some(data.clone());
992                 }
993             });
994             allocator
995         });
996
997         match allocation_crate_data {
998             Some(data) => {
999                 // We have an allocator. We detect separately what kind it is, to allow for some
1000                 // flexibility in misconfiguration.
1001                 let attrs = data.get_item_attrs(CRATE_DEF_INDEX);
1002                 let kind_interned = attr::first_attr_value_str_by_name(&attrs, "rustc_alloc_kind")
1003                     .map(Symbol::as_str);
1004                 let kind_str = kind_interned
1005                     .as_ref()
1006                     .map(|s| s as &str);
1007                 let alloc_kind = match kind_str {
1008                     None |
1009                     Some("lib") => AllocatorKind::DefaultLib,
1010                     Some("exe") => AllocatorKind::DefaultExe,
1011                     Some(other) => {
1012                         self.sess.err(&format!("Allocator kind {} not known", other));
1013                         return;
1014                     }
1015                 };
1016                 self.sess.allocator_kind.set(Some(alloc_kind));
1017             },
1018             None => {
1019                 if !attr::contains_name(&krate.attrs, "default_lib_allocator") {
1020                     self.sess.err("no #[default_lib_allocator] found but one is \
1021                                    required; is libstd not linked?");
1022                     return;
1023                 }
1024                 self.sess.allocator_kind.set(Some(AllocatorKind::DefaultLib));
1025             }
1026         }
1027
1028         fn has_global_allocator(krate: &ast::Crate) -> bool {
1029             struct Finder(bool);
1030             let mut f = Finder(false);
1031             visit::walk_crate(&mut f, krate);
1032             return f.0;
1033
1034             impl<'ast> visit::Visitor<'ast> for Finder {
1035                 fn visit_item(&mut self, i: &'ast ast::Item) {
1036                     if attr::contains_name(&i.attrs, "global_allocator") {
1037                         self.0 = true;
1038                     }
1039                     visit::walk_item(self, i)
1040                 }
1041             }
1042         }
1043     }
1044
1045
1046     fn inject_dependency_if(&self,
1047                             krate: CrateNum,
1048                             what: &str,
1049                             needs_dep: &Fn(&cstore::CrateMetadata) -> bool) {
1050         // don't perform this validation if the session has errors, as one of
1051         // those errors may indicate a circular dependency which could cause
1052         // this to stack overflow.
1053         if self.sess.has_errors() {
1054             return
1055         }
1056
1057         // Before we inject any dependencies, make sure we don't inject a
1058         // circular dependency by validating that this crate doesn't
1059         // transitively depend on any crates satisfying `needs_dep`.
1060         for dep in self.cstore.crate_dependencies_in_rpo(krate) {
1061             let data = self.cstore.get_crate_data(dep);
1062             if needs_dep(&data) {
1063                 self.sess.err(&format!("the crate `{}` cannot depend \
1064                                         on a crate that needs {}, but \
1065                                         it depends on `{}`",
1066                                        self.cstore.get_crate_data(krate).name(),
1067                                        what,
1068                                        data.name()));
1069             }
1070         }
1071
1072         // All crates satisfying `needs_dep` do not explicitly depend on the
1073         // crate provided for this compile, but in order for this compilation to
1074         // be successfully linked we need to inject a dependency (to order the
1075         // crates on the command line correctly).
1076         self.cstore.iter_crate_data(|cnum, data| {
1077             if !needs_dep(data) {
1078                 return
1079             }
1080
1081             info!("injecting a dep from {} to {}", cnum, krate);
1082             data.cnum_map.borrow_mut().push(krate);
1083         });
1084     }
1085 }
1086
1087 impl<'a> middle::cstore::CrateLoader for CrateLoader<'a> {
1088     fn postprocess(&mut self, krate: &ast::Crate) {
1089         // inject the sanitizer runtime before the allocator runtime because all
1090         // sanitizers force the use of the `alloc_system` allocator
1091         self.inject_sanitizer_runtime();
1092         self.inject_profiler_runtime();
1093         self.inject_allocator_crate(krate);
1094         self.inject_panic_runtime(krate);
1095
1096         if log_enabled!(log::LogLevel::Info) {
1097             dump_crates(&self.cstore);
1098         }
1099     }
1100
1101     fn process_item(&mut self, item: &ast::Item, definitions: &Definitions) {
1102         match item.node {
1103             ast::ItemKind::ExternCrate(_) => {
1104                 let info = self.extract_crate_info(item).unwrap();
1105                 let (cnum, ..) = self.resolve_crate(
1106                     &None, info.ident, info.name, None, item.span, PathKind::Crate, info.dep_kind,
1107                 );
1108
1109                 let def_id = definitions.opt_local_def_id(item.id).unwrap();
1110                 let len = definitions.def_path(def_id.index).data.len();
1111
1112                 let extern_crate =
1113                     ExternCrate { def_id: def_id, span: item.span, direct: true, path_len: len };
1114                 self.update_extern_crate(cnum, extern_crate, &mut FxHashSet());
1115                 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
1116             }
1117             _ => {}
1118         }
1119     }
1120 }