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