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