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