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