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