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