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