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