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