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