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