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